Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 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.

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

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

Assuming you're using Bash:

shopt -s extglob
mv !(*.py) some_dir
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 '14 at 13:54