Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

Is there any way to remove all of the files in a directory except for one with a certain filename? For instance, if I had a directory containing the files file1, file2, and dontdelete. Would there be any way to quickly delete file1, and file2 and not dontdelete? I know that I could just do rm file1 file2 but that wouldn't work for a bunch of files. Also, I'm on Mac OS X if that makes a difference.

share|improve this question
Simple wildcarding may be your solution: rm file* will remove file1 and file2 but not dontdelete. If your needs are more complex then, depending shell scripting language, you could generate a list of files you want to delete using a regular expression and pipe this to the rm command. – therobyouknow Jan 1 '11 at 4:57
@Rob: Yeah, my situation is more complex than that. And Ignacio's answer worked. Thanks, though! – Wuffers Jan 1 '11 at 4:59
up vote 15 down vote accepted

In bash:

shopt -s extglob
rm !(dontdelete)
share|improve this answer
Awesome! That worked perfectly! Thanks! – Wuffers Jan 1 '11 at 4:58
+1 Wow very succinct solution. Will bear that in mind if I need it. – therobyouknow Jan 2 '11 at 13:17
can this be extended to include multiple directories that you don't wan to delete – mcgrailm Aug 5 '12 at 12:37

Your Answer


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.