MacOS – Remove all files in folder apart from one using OS X Terminal

macosterminal

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?

Best Answer

I would go about it like this:

find . ! -name <filename> -delete

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

find . ! -name <filename> -exec rm -rv {} \;

This breaks down to

find = find

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

! = not

-name = name

<filename> = 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 <filename>

This command gives you a list of all files and folders in your working directory that are not named <filename>. 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.