删除文件,并在文件-LinuxCLI

问题描述 投票:0回答:6
我试图通过Linux CLI在文件中查找电子邮件地址删除错误的电子邮件。 我可以用

获取文件

find . | xargs grep -l [email protected]

但我不知道如何从那里删除它们,因为以下代码不起作用。

rm -f | xargs find . | xargs grep -l [email protected]

命令的解决方案:

linux file find command-line-interface rm
6个回答
86
投票

or

for file in $(grep -l [email protected] *); do
    rm -i $file;
    #  ^ prompt for delete
done

为了安全起见,我通常将输出从查找到尴尬之类的东西,并创建一个批处理文件,每行为“ RM文件名”

80
投票
难以执行的奇数边缘案例

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

23
投票
-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

3
投票

注:我遇到了GREP无法匹配具有UTF-16编码的文件的问题。 请参阅“解决方法”。如果网站消失了,您要做的就是使用GREP的-A标志,该标志使Grep将文件作为文本并使用与每个扩展字符中任何一个字节匹配的正则表达式图案。例如,匹配属性执行此操作:

grep -a 'Entit.e'

如果那不起作用,请尝试以下操作:

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

尽管您可以确定自己想删除的内容,例如在编写脚本时,我使用的是,我的成功率比以前任何其他任何一个单线都更大:

$ find . | grep -l [email protected] | xargs -I {} rm -rf {}
但我宁愿按名称找到:

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

rm -f `find . | xargs grep -li [email protected]`
做得更好。使用`... .

[email protected]

3
投票
如何删除:
grep -l


Quick和效率。用您要搜索的文本替换
-i
rm
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.