Last Updated: February 25, 2016
·
950
· adziendziel

Delete all files or directories except one.

This is very trivial, but very useful tip for each bash users.
Lets say that there are a few backup files and You want to delete all except newest one.

cd backup_dir && ls
oldest-backup.tar.gz  old-backup.tar.gz   not-as-old-backup.tar.gz   newest-backup.tar.gz

You could remove all of these files individually, but there is a faster solution:

rm !(newest-backup.tar.gz)

Now let's check if it works:

ls
newest-backup.tar.gz

Yeah! You have done it with one line!

p.s. If You want to keep more than one file, add "OR" statement:

rm !(newest-backup.tar.gz | not-as-old-backup.tar.gz)