2

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.

2
  • 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? Apr 11, 2012 at 11:55
  • it's going into a Makefile and I would rather avoid moving files in Makefiles.
    – Menelaos Perdikeas
    Apr 11, 2012 at 13:22

1 Answer 1

7
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
3
  • 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, 2012 at 11:57
  • 1
    In that case, rm !(A|B).jpg Apr 11, 2012 at 13:08
  • @glennjackman Nice!
    – kev
    Apr 11, 2012 at 13:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .