Last Updated: February 25, 2016
·
1.132K
· aaronott

Delete all files except those matching a pattern

Let's say that you just unzipped a file and it dumps all it's contents not into a nice little folder but into the current directory. Now this directory that once had just a couple .zip files contain quite a few other files that you would like to clean up.

Instead of going through one by one, you could either move all the zipped files that were in the directory into another directory and remove the remaining files, or you could use find to remove all the files that don't match *.zip

The second method can be achieved using the find command like so:

find . ! -name '*.zip' -exec rm -r {} \;

This simply reads find from the current directory, all files that do not have a name ending in .zip, and remove them.