【问题标题】:Delete nested hidden files with egrep and xargs使用 grep 和 xargs 删除嵌套的隐藏文件
【发布时间】:2016-02-02 23:47:19
【问题描述】:

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

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

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

【问题讨论】:

    标签: regex bash terminal grep


    【解决方案1】:

    使用find:

    find . -type f -name .\* -exec rm -rf {} \;
    

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

    更好的是:

    find . -name .\* -delete
    

    (感谢@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
    

    这是因为它将输入拆分为空白以提取文件名。我们可以使用另一个分隔符;来自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.
    

    所以:

     find . -type f -name .\* -print0 | xargs -0 rm
    

    【讨论】:

    • 甚至-exec rm -rf {} \;
    • @fedorqui 是的,这也是我会使用的 ;-)
    • 谢谢。即在当前目录中查找隐藏目录,而不是在可见目录中查找隐藏文件。
    • 对不起,我的错误。我做错了。感谢您的帮助!
    • 啊,那是因为-exec 需要被告知要执行的命令(及其参数)在哪里结束,;(所以你总是使用-exec ..... \;)。它被转义以防止 shell 使用它来分隔命令。不客气!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多