删除文件中找到的字符串 - linux cli

Spe*_*hal 45 linux file rm find command-line-interface

我试图通过Linux CLI在文件中查找电子邮件地址来删除错误的电子邮件.

我可以用文件获取

find . | xargs grep -l email@domain.com

但我无法弄清楚如何从那里删除它们,因为以下代码不起作用.

rm -f | xargs find . | xargs grep -l email@domain.com

谢谢您的帮助.

ajr*_*eal 63

@Martin Beckett发表了一个很好的答案,请遵循该指南

您的命令的解决方案:

grep -l email@domain.com * | xargs rm
Run Code Online (Sandbox Code Playgroud)

要么

for file in $(grep -l email@domain.com *); do
    rm -i $file;
    #  ^ prompt for delete
done
Run Code Online (Sandbox Code Playgroud)

  • 如果你有很多文件,这不起作用. (3认同)

Mar*_*ett 60

为了安全起见,我通常将find的输出管道输出到类似awk的内容并创建一个批处理文件,每行为"rm filename"

这样你可以在实际运行它之前检查它并手动修复任何难以用正则表达式做的奇怪边缘情况

find . | xargs grep -l email@domain.com | awk '{print "rm "$1}' > doit.sh
vi doit.sh // check for murphy and his law
source doit.sh
Run Code Online (Sandbox Code Playgroud)


One*_*One 13

您可以使用find-exec-delete,如果它只会删除文件grep命令成功.使用grep -q它不会打印任何东西,你可以替换-qwith -l来查看哪些文件中包含了字符串.

find . -exec grep -q 'email@domain.com' '{}' \; -delete
Run Code Online (Sandbox Code Playgroud)

  • 为我工作,正是我正在寻找的,因为我需要它在一个cron .. (2认同)