Remove all files except for a few, from a folder in Unix [duplicate]

If this is BASH, you could consider using extended globbing. To enable:

shopt -s extglob

(Put that in your .bashrc if you want, or just turn it on when you need it.)

And then, e.g., to delete all the files except filename1 and filename2

rm !(filename1|filename2)

You can also use wildcards like * in there too.

Or you could delete all those matching a pattern:

rm +([0-9])-+([0-9])-+([0-9]).tar

would delete all #-#-#.tar files (where the numbers have 1 or more digits).

It's unclear whether this would meet your needs or not. More details here.


If the filename corresponds with the creation date of the file, it may just be easier to delete files older than a certain day.

This is easily achieved with the find command:

find /home/john/files -type f -mtime +30 -delete

this would delete files under /home/john/files which have a modification date longer than 30 days ago.