使用 rm 递归删除文件和目录

use*_*586 17 unix maintenance rm

是否可以使用 rm 在不使用其他命令的情况下递归删除匹配模式的文件和目录?

war*_*ren 35

直接回答你的问题,“不 - 你不能做你描述的事情rm”。

但是,您可以将其与find. 以下是您可以执行此操作的众多方法之一:

 # search for everything in this tree, search for the file pattern, pipe to rm
 find . | grep <pattern> | xargs rm
Run Code Online (Sandbox Code Playgroud)

例如,如果您想取消所有 *~ 文件,您可以这样做:

 # the $ anchors the grep search to the last character on the line
 find . -type f | grep '~'$ | xargs rm
Run Code Online (Sandbox Code Playgroud)

从评论扩展*

 # this will handle spaces of funky characters in file names
 find -type f -name '*~' -print0 | xargs -0 rm
Run Code Online (Sandbox Code Playgroud)

  • 请小心使用`find | | | xargs rm`。如果有带有空格(或换行符)的文件,这将中断(并且取决于文件名和空格所在的位置)可能会删除您不打算删除的内容。`找到... -print0 | xargs -0 rm` 将更加健壮。但是,这意味着您不能使用`grep`,而必须使用`find` 的谓词来匹配和打印0 只需要的文件。沃伦的第二个例子将更加健壮,因为`find -type f -name '*~' -print0 | xargs -0 rm`。 (10认同)
  • 可能不会直接回答发帖人的问题,但这是他们最接近他们想要的。 (2认同)

Dra*_*kia 8

“不使用其他命令”

不。