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?

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.

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

| improve this answer | |

Assuming you're using Bash:

shopt -s extglob
mv !(*.py) some_dir
| improve this answer | |
ls | grep -v ".py$" | xargs rm
| 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