【问题标题】:Bash - how to find and remove all files that contain a given string?Bash - 如何查找和删除包含给定字符串的所有文件?
【发布时间】:2014-10-20 04:45:41
【问题描述】:

假设给定目录中有许多文件具有各种文件扩展名或根本没有扩展名,只是文件名。其中一些文件包含字符串“\/for\/endetta”。

如何找到并删除该目录中与此模式匹配的所有文件?我可以通过使用来做到这一点:

find -type f -exec egrep -Il '\/for\/endetta' {} \;|xargs rm -fv
  1. 但是没有 xargs 可以做到吗?

  2. 以及如何正确转义 \s 和 /s 等。

【问题讨论】:

  • find -type f -exec grep -q '\/for\/endetta' {} \; -delete 之类的东西应该可以工作(因为 -exec 将获取它运行的命令的退出状态),但我现在没有时间检查它。将-delete 替换为-print 进行检查。
  • 您好,感谢您的尝试。可悲的是它没有用。该命令似乎正在执行(没有引发任何错误),但它没有删除任何包含指定字符串的文件。

标签: design-patterns grep find xargs


【解决方案1】:

使用递归 grep 查找所有文件,然后删除它们。像这样:

for file in $( fgrep -l -r '\/for\/endetta' ../ ); do rm "$file"; done

使用 fgrep 和单引号,您无需转义任何内容。

【讨论】:

    【解决方案2】:

    BrowSlow 的答案(在 cmets 中)是正确的,除了 /for/endetta 的转义。 试试这个命令:

    find . -type f -exec grep -q '\\/for\\/endetta' {} \; -delete 
    

    如果 grep 的退出状态为 true,则执行以下操作。将 -delete 替换为 -print 以查看哪些文件将被删除。

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2013-03-04
      • 2019-06-26
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多