Remove all files in folder apart from one using OS X Terminal I would like to remove the whole content of a folder, apart from one file. The problem is can't copy the file to another folder and then back to the first folder, because then the application doesn't accepts the file, so the one file must stay in the folder.

Exists there a command like I described?
I would go about it like this:

find . ! -name &lt;filename&gt; -delete


for this to work with folders, you have to replace the delete with an exec rm -r

find . ! -name &lt;filename&gt; -exec rm -rv {} \;


This breaks down to

find = find

. = in current working directory, you can replace . with a path, like ~/Documents/

! = not

-name = name

&lt;filename&gt; = file

-exec = execute

rm -rv = verbose remove 

{} = results of the find

\; = close the execution

Find all files and folders in your working folder, that do not have the name filename and then execute the remove command on the results.

You should do a dry run without the delete option, first:

find . ! -name &lt;filename&gt;


This command gives you a list of all files and folders in your working directory that are not named &lt;filename&gt;. Adding -delete or -exec rm -rv {} \;, will delete this files and folder (the exec version).



You could also use

rm -v [^filename]


for folders add -r

rm -rv [^filename]


Somehow I feel more comfortable using the find option. Mainly because you can do a dry run. Either way I would start with a dummy folder and try both options.