Bash specific files delete all

Delete All Files Except Specific Files in Bash

A memo on how to delete all files except specific files in Bash. When you want to delete files that don't match or aren't specified with the rm command in Linux command line Bash language.

Shou Arisaka
1 min read
Oct 2, 2025

A memo on how to delete all files except specific files in Bash.

When you want to delete files that don’t match or aren’t specified with the rm command in Linux command line Bash language.

Looking at https://stackoverflow.com/questions/4325216/remove-all-files-except-some-from-a-directory, there are various approaches which is impressive, but the simplest and most understandable is probably the following:

e.g. rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)

Delete all except .wav files in a folder rm !(*.wav)

Also, find . -type f -not -name ‘*.wav’ | xargs rm didn’t work when there were filenames with spaces.

Share this article

Shou Arisaka Oct 2, 2025

🔗 Copy Links