Linux: Removing files that don’t contain all the words specified

bashfilelinuxshell

Inside a directory, how can I delete files that lack any of the words specified, so that only files that contain ALL the words are left? I tried to write a simple bash shell script using grep and rm commands, but I got lost. I am totally new to Linux, any help would be appreciated

Best Solution

How about:

grep -L foo *.txt | xargs rm
grep -L bar *.txt | xargs rm

If a file does not contain foo, then the first line will remove it.

If a file does not contain bar, then the second line will remove it.

Only files containing both foo and bar should be left

-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.

See also @Mykola Golubyev's post for placing in a loop.