Linux:删除不包含指定的所有单词的文件

Dan*_*iel 11 linux bash shell file

在目录中,如何删除缺少任何指定单词的文件,以便只保留包含所有单词的文件?我尝试使用grep和rm命令编写一个简单的bash shell脚本,但我迷路了.我是Linux新手,任何帮助都将不胜感激

too*_*kit 21

怎么样:

grep -L foo *.txt | xargs rm
grep -L bar *.txt | xargs rm
Run Code Online (Sandbox Code Playgroud)

如果文件确实包含foo,则第一行会删除它.

如果文件确实包含bar,则第二线将其删除.

同时包含只有文件foobar应留

-L, --files-without-match
     Suppress normal output; instead print the  name  of  each  input
     file from which no output would normally have been printed.  The
     scanning will stop on the first match.
Run Code Online (Sandbox Code Playgroud)

另见@Mykola Golubyev的帖子放置循环.


Myk*_*yev 11

list=`Word1 Word2 Word3 Word4 Word5`
for word in $list
    grep -L $word *.txt | xargs rm
done
Run Code Online (Sandbox Code Playgroud)


sou*_*rge 5

除上述答案外:使用换行符作为分隔符来处理带空格的文件名!

grep -L $word $file | xargs -d '\n' rm
Run Code Online (Sandbox Code Playgroud)