Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

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

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

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

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers 4

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.

share|improve this answer
ls | grep -v ".py$" | xargs rm
share|improve this answer
    
Using ls for anything but human readable output is generally a bad idea. And parsing it is even worse. Use find instead. –  Livius Mar 9 at 13:54
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.

share|improve this answer

Assuming you're using Bash:

shopt -s extglob
mv !(*.py) some_dir
share|improve this answer