Possible Duplicate:
Remove all files but one with rm

This is a very simple question and i dont know whether a solution exists or not.

I have some files in a directory, assume i have .py and some other extension files. now i would like to remove all files except those that end in .py files. How could i do that with the rm command?

That is i want something like

!(rm *.py) 

Is it possible?

link|improve this question
feedback

migrated from stackoverflow.com May 5 '11 at 13:51

This question came from our site for professional and enthusiast programmers.

closed as exact duplicate by Ignacio Vazquez-Abrams, Sathya May 5 '11 at 14:59

This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question. See the FAQ for guidance on how to improve it.

4 Answers

shopt -s extglob
rm !(*.py)

You enable the extglob variable. This gives you some extra pattern matching features, particularly negation.

You can disable it again with shopt -u extglob.

link|improve this answer
feedback

Assuming you're using Bash:

shopt -s extglob
mv !(*.py) some_dir
link|improve this answer
feedback
ls | grep -v ".py$" | xargs rm
link|improve this answer
feedback

Easy to remember is find:

find -not -name "*.py" -delete 

It will delete files in subdirs too, compared to the larsmas solution, but you can prevent that with the -maxdepth parameter.

Not every find implementation might support the delete option. Gnu find does since version 4.2.3.

link|improve this answer
feedback