SoFunction
Updated on 2025-03-09

3 ways to delete all files outside certain files in shell

A colleague of mine once asked me a question: How to delete all files in a directory except some files under Linux? At that time, I told him that it could be solved by pattern matching. But in fact, there are other methods besides this, as the saying goes, "All roads lead to Rome." Let's take a look one by one.

Assuming you want to delete all files in the ~/Downloads directory except *.iso and *.zip, you can handle them in bash as follows:

Method 1: Pattern Matching Method

Copy the codeThe code is as follows:

shopt -s extglob # Confirm to enable the extglob option
cd ~/Downloads
rm -v !(*.iso|*.zip)
!(pattern list) is used to match files other than pattern list.

Method 2: Set variable method

In bash, GLOBIGNORE can be used to set the pattern matching file to be ignored, and multiple patterns are separated by:.

Copy the codeThe code is as follows:

cd ~/Downloads
export GLOBIGNORE=*.zip:*.iso
rm -v *
unset GLOBIGNORE

Method 3: find search method

Friends who are familiar with find must know that find is extremely powerful, so using it can also solve this problem.

Copy the codeThe code is as follows:

cd ~/Downloads
find . -type f -not \( -name '*.zip' -or -name '*.iso' \) -delete

However, I still want to remind everyone that rm operation is very dangerous, so don’t show off your skills. If you are not at ease, you can delete it honestly one by one or in batches first, which is much more convenient than retrieving it afterwards.