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

时间:2010-12-25 02:53:17

标签: linux file find command-line-interface rm

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

我可以使用

获取文件

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

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

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

感谢您的协助。

7 个答案:

答案 0 :(得分:62)

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

您的命令的解决方案:

grep -l email@domain.com * | xargs rm

或者

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

答案 1 :(得分:57)

为了安全起见,我通常将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

答案 2 :(得分:13)

您可以使用find的{​​{1}}和-exec,它只会在-delete命令成功时删除该文件。使用grep因此无法打印任何内容,您可以将grep -q替换为-q,以查看哪些文件中包含字符串。

-l

答案 3 :(得分:2)

尽管马丁安全回答,如果您确定要删除的内容,例如编写脚本,我已经使用this取得了比任何成功更大的成功在此之前建议的其他单线:

$ find . | grep -l email@domain.com | xargs -I {} rm -rf {}

但我宁愿找到名字:

$ find . -iname *something* | xargs -I {} echo {}

答案 4 :(得分:2)

我喜欢Martin Beckett的解决方案,但发现带有空格的文件名可以将其绊倒(就像谁在文件名中使用空格,pfft:D)。此外,我想查看匹配的内容,以便将匹配的文件移动到本地文件夹,而不是仅使用'rm'命令删除它们:

# Make a folder in the current directory to put the matched files
$ mkdir -p './matched-files'

# Create a script to move files that match the grep
# NOTE: Remove "-name '*.txt'" to allow all file extensions to be searched.
# NOTE: Edit the grep argument 'something' to what you want to search for.

$ find . -name '*.txt' -print0 | xargs -0 grep -al 'something' | awk -F '\n' '{ print "mv \""$0"\" ./matched-files" }' > doit.sh

Or because its possible (in Linux, idk about other OS's) to have newlines in a file name you can use this longer, untested if works better (who puts newlines in filenames? pfft :D), version:

$ find . -name '*.txt' -print0 | xargs -0 grep -alZ 'something' | awk -F '\0' '{ for (x=1; x<NF; x++) print "mv \""$x"\" ./matched-files" }' > doit.sh

# Evaluate the file following the 'source' command as a list of commands executed in the current context:
$ source doit.sh

注意:我遇到过grep无法与具有utf-16编码的文件匹配的问题。 有关解决方法,请参阅here。如果网站消失了你要做的就是使用grep的-a标志,它使grep将文件视为文本,并使用与每个扩展字符中的任何第一个字节匹配的正则表达式模式。例如,要匹配Entité,请执行以下操作:

grep -a 'Entit.e'

如果这不起作用,那么试试这个:

grep -a 'E.n.t.i.t.e'

答案 5 :(得分:1)

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

做得更好。使用`...`来运行命令以提供包含电子邮件的文件名。@ domain.com(grep -l列出它们,-i忽略大小写)以使用rm(-f强制/ -i交互式)删除它们。

答案 6 :(得分:0)

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

如何删除:

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