How to Remove Files Without a Certain Extension?


You have a directory with a lot of files, and you want to delete only the files that don’t match a specific extension.

This is a simple task when using the find command-line utility.

Delete a single extension

You can delete all files that do not have the following *.txt extension:

find . -type f ! -name "*.txt" -exec rm {} \;

Delete multiple extensions

You can delete all files that do not have the following *.txt or *.exe extensions.

find . -type f ! -name "*.exe" ! -name "*.txt" -exec rm {} \;