使用egrep和xargs删除嵌套的隐藏文件

125*_*748 1 regex bash terminal grep

我正在尝试删除所有隐藏的目录和文件,并递归删除它们.当前目录级别唯一隐藏的目录是.,..但几个目录中的每个目录都有几个隐藏文件(以其开头._).ls -aR | egrep '^\.\w+' |将列出我想要的所有文件,但添加'| xargs'rm'`给了我rm错误"没有这样的文件或目录".

我认为这意味着我要删除的每个目录都需要附加它的父目录和/.但也许我错了.

如何更新此命令以删除这些文件?

Ken*_*ney 5

用途find:

find . -type f -name .\* -exec rm -rf {} \;
Run Code Online (Sandbox Code Playgroud)

-exec是空白安全的:{}将通过文件路径(相对于.)作为单个参数来rm.

更好的是:

find . -name .\* -delete
Run Code Online (Sandbox Code Playgroud)

(感谢@ John1024).第一种形式为找到的每个文件生成一个进程,而第二种形式则没有.

xargs 默认情况下不是白色空间安全:

$ touch a\ b
$ find . -maxdepth 1 -name a\ \* | xargs rm
rm: cannot remove ‘./a’: No such file or directory
rm: cannot remove ‘b’: No such file or directory
Run Code Online (Sandbox Code Playgroud)

这是因为它将它在白色空间上的输入分开以提取文件名.我们可以使用另一个分隔符; 来自man find:

  -print0
          True; print the full file name on the standard output,  followed
          by  a  null  character  (instead  of  the newline character that
          -print uses).  This allows file names that contain  newlines  or
          other  types  of white space to be correctly interpreted by pro?
          grams that process the find output.  This option corresponds  to
          the -0 option of xargs.
Run Code Online (Sandbox Code Playgroud)

所以:

 find . -type f -name .\* -print0 | xargs -0 rm
Run Code Online (Sandbox Code Playgroud)

  • 啊,那是因为`-exec`需要告诉执行命令(和它的参数)在哪里结束,```(所以你总是使用`-exec ..... \;`).它被转义以防止shell使用它来分离命令.别客气! (2认同)