Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove files when name does NOT contain some words

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!

like image 760
DocWiki Avatar asked Jul 03 '11 09:07

DocWiki


People also ask

How do I remove a file with the name '- something?

How do I remove or access a file with the name '-something' or containing another strange character ? If your file starts with a minus, use the -- flag to rm; if your file is named -g, then your rm command would look like rm -- -g.

Which commands are used to remove files?

Use the rm command to remove files you no longer need. The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory.


3 Answers

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

like image 198
EdoDodo Avatar answered Oct 17 '22 05:10

EdoDodo


With bash, you can get "negative" matching via the extglob shell option:

shopt -s extglob
rm !(*good*)
like image 22
glenn jackman Avatar answered Oct 17 '22 04:10

glenn jackman


You can use find with the -not operator:

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

I've used -exec to call rm there, but I wonder if find has a built-in delete action it does, see below.

But very careful with that. Note in the above I've had to put an -a -not -name "." clause in, because otherwise it matched ., the current directory. So I'd test thoroughly with -print before putting in the -exec rm {} \; bit!

Update: Yup, I've never used it, but there is indeed a -delete action. So:

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

Again, be careful and double-check you're not matching more than you want to match first.

like image 36
T.J. Crowder Avatar answered Oct 17 '22 06:10

T.J. Crowder