Delete files when the name does NOT contain some words

I am using Linux and intend to delete some files using the shell.

I have several files in my folder, some file names contain the word "good", others do not. For example:

ssgood.wmv ssbad.wmv goodboy.wmv cuteboy.wmv 

I want to delete files that DO NOT contain a “good” in the name, so the rest of the files:

 ssgood.wmv goodboy.wmv 

How to do this with rm in a shell? I'm trying to use

 rm -f *[!good].* 

but that will not work.

Thank you so much!

+7
source share
3 answers

This command should do what you need:

 ls -1 | grep -v 'good' | xargs rm -f 

It will probably work faster than other commands, since it is not related to using a regular expression (which is slow and unnecessary for such a simple operation).

+16
source

With bash, you can get a "negative" match using the extglob shell extglob :

 shopt -s extglob rm !(*good*) 
+6
source

You can use find with the -not operator:

 find . -not -iname "*good*" -a -not -name "." -exec rm {} \; 

I used -exec to call rm there, but I wonder if find built-in delete action , see below.

But be very careful with that. Please note that in the above I had to put the sentence -a -not -name "." because otherwise he matched . , current directory. Therefore, I thoroughly tested -print before inserting the -exec rm {} \; bit -exec rm {} \; !

Update : Yes, I never used it, but there really is a -delete action. So:

 find . -not -iname "*good*" -a -not -name "." -delete 

Again, be careful and double-check that you do not match more than you want at first.

+4
source

All Articles