59

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.

terdon
  • 98,183
  • 15
  • 197
  • 293
Maythux
  • 82,867
  • 54
  • 239
  • 271
  • 1
    I think [this](http://askubuntu.com/questions/256521/removing-files-with-a-certain-extension-except-one-file-from-terminal) might explain. ;) – JoKeR May 16 '15 at 12:20
  • I've come to this before, but this needs more work – Maythux May 16 '15 at 12:21
  • These questions are confusing me, not to mention they have no idea how many files are on your system with . Or .txt, use this command simple to use and easy to understand rm -riv ~/Desktop/path/* * = all in folder , r = recursive , v = verbose , i = prompt you before deleting –  Apr 09 '17 at 23:56

5 Answers5

99

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)
lhrec_106
  • 101
  • 4
Maythux
  • 82,867
  • 54
  • 239
  • 271
23

You can try this command:

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

But you need be careful because find command is recursive.

Maythux
  • 82,867
  • 54
  • 239
  • 271
cosmoscalibur
  • 1,660
  • 17
  • 23
12

You can do this in terminal:

cd dirA 
export GLOBIGNORE=a.txt
rm *
export GLOBIGNORE=
Maythux
  • 82,867
  • 54
  • 239
  • 271
Sharad Gautam
  • 2,480
  • 2
  • 12
  • 24
5

You can use the command :

find ! -name 'a.txt' -type f -exec rm -f {} +

This will look for files (-type f) in the current directory except for file a.txt (! -name 'a.txt) and then will remove them (-exec rm -f {} +)

Maythux
  • 82,867
  • 54
  • 239
  • 271
Sh1d0w
  • 1,348
  • 8
  • 16
5

Use find and xargs

find folder -type f -not -name 'a.txt' -print0 | xargs -0 rm

To exclude multiple things:

find folder -type f -not -name 'a.txt' -not -name 'b.txt' -print0 | xargs -0 rm

This also works with wildcards:

find folder -type f -not -name '*.png' -not -name 'b.txt' -print0  | xargs -0 rm

To search in the current folder, use . in place of 'folder'.

Base source

Tim
  • 32,274
  • 27
  • 118
  • 177