Linux – Remove files that start with but don’t contain

filenameslinuxrm

I'm trying to remove a lot of files at once but need to be specific as to not remove any of the files I actually need.

I have a ton of corrupt files that start master- but there are valid files that start with master-2018

So, I want to do something like

rm -rf master-* --exclude master-2018*

Is that I need possible?

Best Answer

Yes you can use more than one pattern with find:

$ find -name 'master-*' \! -name 'master-2018*' -print0 -prune |
     xargs -0 echo rm -fr

(remove the echo if you're satisfied with the dry run)

You should add a -maxdepth 1 predicate just after find if you only want ro remove files from the current directory, ie master-1991 but no subdir/master-1991.

Related Question