Deleting all files in a folder except files X, Y, and Z

Instead of using rm, it may be easier to use find. A command like this would delete everything except a file named exactly 'file'

find . \! -name 'file' -delete

Many versions of should be able to support globbing and regular expression matching.

You could also pipe the output of find to rm as well

find . \! -name '*pattern*' -print0 | xargs --null rm 

Using zsh, with setopt EXTENDED_GLOB, using the ~ operator (except)

rm -- *~(x|y|z)

or ^ operator (negation):

rm -- ^(x|y|z)

But, you should probably instead move the files elsewhere, then delete everything. It's far safer in terms of finger slips, such as hitting enter too soon.


ls -1 | grep -v "^[XYZ]$" # | xargs rm -r

Attention: Run the command and if the files to be deleted are the right ones, run it again and delete the hash character "#".

If the filenames are more complicated then that, do

ls -1 | egrep -v "^file1$|^filename2$|^f1le$" # | xargs rm -r

Again, first look at the results then remove the hash sign.

This version - as suggested in the comments - saves some characters and looks a bit clearer.

ls -1 | egrep -v "^(file1|filename2|f1le)$" # | xargs rm -r