Remove everything except?

5

Possible Duplicate:
Remove all files but one with rm

In unix, to remove zip files in a directory one can simply type

rm *.zip

How can one remove everything except zip files?

dzhelil

Posted 2011-01-17T03:09:07.780

Reputation: 430

Question was closed 2011-01-17T04:11:24.180

Answers

8

rm !(*.zip)

This appears to work. The ! represents "not".

extglob needs to be enabled in the shell behavior settings for this to work. It is probably already enabled... but if not, enable it with:

shopt -s extglob

And after answering this... indeed Ignacio Vazquez-Abrams you are correct. It is pretty much duplicate.

James T

Posted 2011-01-17T03:09:07.780

Reputation: 8 515

Thank you for adding the mention of extglob! I was able to run this command in the normal interactive prompt without a hitch, but then when trying something like echo !(*.zip) in a script, I would always get a syntax error. Adding that option fixed it! – eacousineau – 2014-05-04T13:57:52.950

0

Try creating a list then removing the file from the list.

Ex.

ls $yourDir | grep -v .zip > deleteThis.list

the call

xargs rm < deleteThis.list

Dan M.

Posted 2011-01-17T03:09:07.780

Reputation: 1 676

@JohnT I know you posted that answer more than six years ago, but it helped me today. Thank you!!! – ShiningLight – 2017-08-17T20:17:50.067

3Why not just rm $(ls | grep -v *.zip) ? :) – John T – 2011-01-17T04:02:20.393

There's that too! :) – Dan M. – 2011-01-17T16:28:03.277