Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 211
Daniel Avatar asked Mar 05 '09 12:03

Daniel


People also ask

How do I delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

Which command is used in Linux to remove a directory which contains some files?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


1 Answers

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.

like image 95
toolkit Avatar answered Sep 17 '22 13:09

toolkit