Jim Bo
Jim Bo

Reputation: 657

Using find to delete all files with a given name except the one with a given extension

I want to delete all files in a directory with a given name, except for one with a given extension. I.e. we have a directory with:

foo.txt foo.exe foo.jpg foo.png foo.something foo.somethingelse bar.jpg bar.exe

I want to get rid of foo.txt foo.jpg foo.png foo.something foo.somethingelse

BUT crucially I don't want to get rid of foo.exe

Is there an easy one liner to do this?

Thank you

Upvotes: 4

Views: 2862

Answers (1)

Nate Kohl
Nate Kohl

Reputation: 35914

You can use ! inside a find command to exclude things, so something like:

find . -maxdepth 1  -type f  -name "foo.*"  ! -name foo.exe  -exec rm '{}' \;
       -----------  -------  -------------  ---------------  ----------------
       in this dir   files    named foo.*   but not foo.exe  ...destroy them.

That should delete files matching foo.* in the current directory but leave foo.exe alone.

Upvotes: 7

Related Questions