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
Join Stack Overflow to learn, share knowledge, and build your career.
|
How about:
If a file does not contain If a file does not contain Only files containing both
See also @Mykola Golubyev's post for placing in a loop. |
|||||||||||||||||||||
|
|
To do the same matching filenames (not the contents of files as most of the solutions above) you can use the following:
As per comments:
shouldn't be used. The below does the same thing without using the
The -ve reverses the search for the regexp pattern for either foo or bar in the filename. Any further words to be added to the list need to be separated by \| e.g. one\|two\|three |
|||||||||
|
|
You could try something like this but it may break if the patterns contain shell or grep meta characters: (in this example one two three are the patterns)
|
|||
|
|
|
Addition to the answers above: Use the newline character as delimiter to handle file names with spaces!
|
||||
|
|
|
grep -L word | xargs rm |
|||
|
|
|
|||
|
|
|
First, remove the file-list:
Then, for each of the words, add the file to the filelist if it contains that word:
Then sort, uniqify and get a count:
All those files in flsit_with_count that don't have the number of words should be deleted. The format will be:
If there were 8 words, then file1 and file2 should be deleted. I'll leave the writing/testing of the script to you. Okay, you convinced me, here's my script:
This removes the files in the directory that didn't have all three words: |
||||
|
|
|
This will remove all files that doesn't contain words Ping or Sent
|
|||||||||
|