Here is the situation.
I have a directory which contains many files with different extensions. I want to delete all files except one with a specific name.
This could be easily done using the GUI by selecting all and pressing ctrl and deselecting the file in question.
That is exactly what I want to, but how can I do it from the command line?
For example: dirA contains the following files:
a.txt
b.txt
c.php
d.html
a.db
b.db
e.html
I want to delete all files keeping only the file named a.txt
.
I've come with this easy simple great command:
you can use ! as a negation
Test the glob with echo first i.e.
If it doesn't work, for
bash
you may need to enable this withIf you wanted to keep both
a.txt
andb.txt
, you can use!(a.txt|b.txt)
or!([ab].txt)
.Edit:
to make
rm
working recursively just add-r
likeand also, it is working with folder. just need to change the name to the dir name, such as for
a_dir
You can try this command:
But you need be careful because find command is recursive.
You can do this in terminal:
You can use the command :
This will look for files (
-type f
) in the current directory except for filea.txt
(! -name 'a.txt
) and then will remove them (-exec rm -f {} +
)Use
find
andxargs
To exclude multiple things:
This also works with wildcards:
To search in the current folder, use
.
in place of 'folder'.Base source