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

This question already has an answer here:

I need to delete all files, except one (its name is defined), from a given directory.

How can I do this from the terminal in OS X? Can I do this with one single command?

share|improve this question

migrated from stackoverflow.com May 31 '12 at 8:40

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

marked as duplicate by DavidPostill, fixer1234, karel, MariusMatutiae, Dave Jun 30 '15 at 11:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 6 down vote accepted
shopt -s extglob && rm !(non_delete_file)

or

rm -f !(non_delete_file)

or

find . ! -name non_delete_file -delete

Note that the above find command will work recursively -- it will delete all files and directories in the current directory, and in all subdirectories. If that is a problem, use -type f (to match only files) and -maxdepth 1 (to match things only in the current directory, ignoring subdirectories)

find . -type f -maxdepth 1 ! -name non_delete_file -delete
share|improve this answer
    
+1, you arrived just a second before me with find command :) – DonCallisto May 30 '12 at 8:00
    
@DonCallisto, sorry, i don't know, next time i'll wait you :) – shk May 30 '12 at 8:02
    
It's a good solution but how to avoid deleting system file like ./.DS_Store? Also with respect to the -name non_delete_file, in my case -name non_delete_file is a directory. I would it to spare it as well as the content inside. – Konrad Jan 19 at 11:28
  1. move the file that you want to preserve to somewhere outside the directory
  2. remove everything in the directory using your favourite method
  3. move the file that you want to preserve back into the directory

Not exactly 'hi-tech' but it is much harder to accidentally delete the file that you want to preserve if you use this approach.

Obviously, this approach fails if the file needs to continuously exist in the directory while all the carnage is happening.

share|improve this answer

Try

rm `ls | grep -v '^defined$'`
share|improve this answer
    
And what about not_defined? – Ignacio Vazquez-Abrams May 30 '12 at 7:58
    
Fixed with anchors. – Christian Varga May 30 '12 at 8:00
    
Don't parse ls (this answer will specifically break on files with spaces in their names). you could use printf %s\\n * instead of ls for more reliability (though that will still break on files with newlines in their names...) – evilsoup Jul 31 '13 at 18:30