我正在尝试根据通过 Linux CLI 在文件中查找电子邮件地址来删除错误的电子邮件。
我可以用
find . | xargs grep -l email@domain.com
但我不知道如何从那里删除它们,因为下面的代码不起作用。
rm -f | xargs find . | xargs grep -l email@domain.com
谢谢您的帮助。
我正在尝试根据通过 Linux CLI 在文件中查找电子邮件地址来删除错误的电子邮件。
我可以用
find . | xargs grep -l email@domain.com
但我不知道如何从那里删除它们,因为下面的代码不起作用。
rm -f | xargs find . | xargs grep -l email@domain.com
谢谢您的帮助。
为了安全起见,我通常将 find 的输出通过管道传输到 awk 之类的东西,并创建一个批处理文件,每行都是“rm 文件名”
这样,您可以在实际运行之前对其进行检查,并手动修复任何使用正则表达式难以处理的奇怪边缘情况
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
@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
您可以使用find
's-exec
和-delete
,它只会在grep
命令成功时删除文件。使用grep -q
so 它不会打印任何内容,您可以替换-q
以-l
查看哪些文件中有字符串。
find . -exec grep -q 'email@domain.com' '{}' \; -delete
尽管 Martin 给出了安全的答案,但如果您确定要删除的内容,例如在编写脚本时,我使用它比之前在这里建议的任何其他单行词更成功:
$ find . | grep -l email@domain.com | xargs -I {} rm -rf {}
但我宁愿按名称查找:
$ find . -iname *something* | xargs -I {} echo {}
我喜欢 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 编码的文件的问题。请参阅此处了解解决方法。如果该网站消失,您所做的是使用 grep 的 -a 标志,该标志使 grep 将文件视为文本并使用匹配每个扩展字符中的任何第一个字节的正则表达式模式。例如要匹配 Entité,请执行以下操作:
grep -a 'Entit.e'
如果这不起作用,那么试试这个:
grep -a 'E.n.t.i.t.e'
rm -f `find . | xargs grep -li email@domain.com`
does the job better. Use `...` to run the command to offer the file names containing email.@domain.com (grep -l lists them, -i ignores case) to remove them with rm (-f forcibly / -i interactively).
find . | xargs grep -l email@domain.com
如何删除:
rm -f 'find . | xargs grep -l email@domain.com'