Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.