获取文件
find . | xargs grep -l [email protected]
但我不知道如何从那里删除它们,因为以下代码不起作用。
rm -f | xargs find . | xargs grep -l [email protected]
命令的解决方案:
or
for file in $(grep -l [email protected] *); do
rm -i $file;
# ^ prompt for delete
done
为了安全起见,我通常将输出从查找到尴尬之类的东西,并创建一个批处理文件,每行为“ RM文件名”
find . | xargs grep -l [email protected] | awk '{print "rm "$1}' > doit.sh
vi doit.sh // check for murphy and his law
source doit.sh
您可以使用
find
-exec
和
-delete
,只有在grep
命令成功时才会删除文件。使用grep -q
,因此它不会打印任何东西,您可以用-q
替换-l
查看其中的字符串。
find . -type f -exec grep -q '[email protected]' '{}' \; -delete
我喜欢马丁·贝克特(Martin Beckett)的解决方案,但发现带有空格的文件名称可以绊倒(就像谁在文件名中使用了pfft:d: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将文件作为文本并使用与每个扩展字符中任何一个字节匹配的正则表达式图案。例如,匹配属性执行此操作:
grep -a 'Entit.e'
$ find . | grep -l [email protected] | xargs -I {} rm -rf {}
但我宁愿按名称找到:$ find . -iname *something* | xargs -I {} echo {}
rm -f `find . | xargs grep -li [email protected]`
做得更好。使用`... .
[email protected]
grep -l
Quick和效率。用您要搜索的文本替换
-i
。
rm