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:

1
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.

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