In a Linux script, how to remove all files & directories but one, in current directory? In a Linux script, how to remove all files & directories but one, in current directory? shell shell

In a Linux script, how to remove all files & directories but one, in current directory?


find . -mindepth 1 -maxdepth 1 ! -iname nameoffiletokeep -print0| xargs -0 rm -rf;

This finds all files and directories that are direct children of the current working directory that are not named nameoffiletokeep and removes them all (recursively for directories), regardless of leading dots (e.g. .hidden, which would be missed if you used a glob like rm -rf *), spaces, or other metachars in the file names.

I've used -iname for case-insensitive matching against nameoffiletokeep, but if you want case-sensitivity, you should use -name. The choice should depend on the underlying file system behavior, and your awareness of the letter-case of the file name you're trying to protect.


If you are using bash, you can use extended globbing:

shopt -s extglobrm -fr !(nameoffiletokeep)

In zsh the same idea is possible:

setopt extended_globrm -fr ^nameoffiletokeep