# bash extended globs :: rm all *.jpg files except two particular ones

Can I use Bash extended glob patterns to implement logical 'AND' ? Say I have a folder of jpg files (among others) and I want to rm all jpg files except A.jpg and B.jpg. How would I do that without trying tricks like remaming the files temporarily and so on ? I guess the general theme is how one can combine logical expressions and negations in Bash extended globs.

-

## migrated from stackoverflow.comApr 12 '12 at 7:43

This question came from our site for professional and enthusiast programmers.

Unless this is to be done several times, why not just move the files you want to save to a temporary directory, and then move them back when you're done? –  Joachim Pileborg Apr 11 '12 at 11:55
it's going into a Makefile and I would rather avoid moving files in Makefiles. –  Menelaos Perdikeas Apr 11 '12 at 13:22

shopt -s extglob
rm !(A|B).jpg


!(pattern-list) Matches anything except one of the given patterns.
pattern-list is a list of one or more patterns separated by a ‘|’

You can also use find:

find . -name '*.jpg' ! -name '[AB].jpg' -delete

-
Thanks but there may be other kinds of files as well in the folder, i.e. not just jpgs (I've edited my original question to make it explicit). –  Menelaos Perdikeas Apr 11 '12 at 11:57
In that case, rm !(A|B).jpg –  glenn jackman Apr 11 '12 at 13:08
@glennjackman Nice! –  kev Apr 11 '12 at 13:10