How to delete all files except one named file from a specific folder

I've come with this easy simple great command:

rm !(a.txt)

you can use ! as a negation

Test the glob with echo first i.e.

echo !(a.txt)

If it doesn't work, for bash you may need to enable this with

shopt -s extglob

If you wanted to keep both a.txt and b.txt, you can use !(a.txt|b.txt) or !([ab].txt).

Edit:

to make rm working recursively just add -r like

rm -r !(a.txt)

and also, it is working with folder. just need to change the name to the dir name, such as for a_dir

rm -r !(a_dir)

You can try this command:

find . \! -name 'a.txt' -delete

But you need be careful because find command is recursive.


You can do this in terminal:

cd dirA 
export GLOBIGNORE=a.txt
rm *
export GLOBIGNORE=

Tags:

Command Line