Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

migrated from stackoverflow.com Apr 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
up vote 5 down vote accepted
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
share|improve this answer
    
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
1  
In that case, rm !(A|B).jpg – glenn jackman Apr 11 '12 at 13:08
    
@glennjackman Nice! – kev Apr 11 '12 at 13:10

You must log in to answer this question.

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