remove files when name does NOT contain some words

DocWiki picture DocWiki · Jul 3, 2011 · Viewed 13.9k times · Source

I am using Linux and intend to remove some files using shell.

I have some files in my folder, some filenames contain the word "good", others don't. For example:

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

I want to remove the files that does NOT contain "good" in the name, so the remaining files are:

ssgood.wmv
goodboy.wmv

How to do that using rm in shell? I try to use

rm -f *[!good].*

but it doesn't work.

Thanks a lot!

Answer

EdoDodo picture EdoDodo · Jul 3, 2011

This command should do what you you need:

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

It will probably run faster than other commands, since it does not involve the use of a regex (which is slow, and unnecessary for such a simple operation).