从目录及其子项中删除所有文件类型

Wil*_*ill 30 unix bash shell scripting

我的印象是

rm -r *.xml
Run Code Online (Sandbox Code Playgroud)

会删除父母和孩子的所有文件:

*.xml: No such file or directory
Run Code Online (Sandbox Code Playgroud)

Vij*_*jay 46

rm的手册页说:

 -r, -R, --recursive
          remove directories and their contents recursively
Run Code Online (Sandbox Code Playgroud)

这意味着该标志-r正在等待一个目录.但*.xml不是目录.

如果要以递归方式从当前目录中删除所有.xml文件,则命令为:

find . -name "*.xml" -type f|xargs rm -f
Run Code Online (Sandbox Code Playgroud)

  • @noa实际上`xargs`效率更高.`-exec`为每个匹配的文件调用`rm`,而`xargs`分批调用它.当有大量文件时,这会产生很大的不同. (6认同)
  • 无需调用xargs; 使用`find -exec`. (4认同)

Sha*_*hin 28

我假设你想要*.xml递归删除所有文件(在当前和所有子目录中).为此,请使用find:

find . -name "*.xml" -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)

另一方面,递归删除让我感到害怕.在我的日子里,我倾向于在这一步骤之前:

find . -name "*.xml" 
Run Code Online (Sandbox Code Playgroud)

(没有-exec位)只是为了看看在跳跃之前可能会删除什么.我建议你这样做.你的文件会谢谢你.


mad*_*adc 6

阅读有关查找空目录 unix 的答案,我刚刚了解了 -delete 操作:

-delete
          Delete  files; true if removal succeeded.  If the removal failed, an error message is issued.  If -delete fails, find's exit status will be nonzero (when it even?
          tually exits).  Use of -delete automatically turns on the -depth option.

          Warnings: Don't forget that the find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the start?
          ing  points  you  specified.   When  testing a find command line that you later intend to use with -delete, you should explicitly specify -depth in order to avoid
          later surprises.  Because -delete implies -depth, you cannot usefully use -prune and -delete together.
Run Code Online (Sandbox Code Playgroud)

来源:男人发现

这意味着,您还可以像这样递归地删除所有 xml 文件:

find . -name "*.xml" -type f -delete
Run Code Online (Sandbox Code Playgroud)