How can delete all files except one from a directory?

2

1

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?

Yuriy Velichko

Posted 2012-05-30T07:53:52.493

Reputation:

Question was closed 2015-06-30T11:57:45.983

Answers

9

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

shk

Posted 2012-05-30T07:53:52.493

Reputation: 248

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 – 2016-01-19T11:28:32.677

+1, you arrived just a second before me with find command :) – DonCallisto – 2012-05-30T08:00:56.753

@DonCallisto, sorry, i don't know, next time i'll wait you :) – None – 2012-05-30T08:02:24.177

1

  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.

Daniel Boulet

Posted 2012-05-30T07:53:52.493

Reputation: 11

0

Try

rm `ls | grep -v '^defined$'`

Christian Varga

Posted 2012-05-30T07:53:52.493

Reputation: 109

And what about not_defined? – Ignacio Vazquez-Abrams – 2012-05-30T07:58:46.583

Fixed with anchors. – None – 2012-05-30T08:00:40.367

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 – 2013-07-31T18:30:31.560