How to remove all files except some?

How can I remove all files in a directory but just keep some specified ones?

There are multiple ways to do this..

Way 1: Use extglob

shopt -s extglob # Make sure extglob is enabled
cd ~/Downloads
rm -v !(*.iso|*.zip)

Way 2: Use the variable GLOBIGNORE

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

Way 3: Use find

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

Way 4: On your own
We can make a directory in /tmp, and move the excepted files there, then move it back:

mkdir /tmp/a
cd ~/Downloads
mv *.zip *.iso /tmp/a
rm *
Share Button

Leave a comment

Your email address will not be published. Required fields are marked *