Is there a quick way of deleting all the .pyc files from a tree of directories?


If you've got GNU find then you probably want

find <directory name> -name '*.pyc' -delete

If you need something portable then you're better off with

find <directory name> -name '*.pyc' -exec rm {} \;

If speed is a big deal and you've got GNU find and GNU xargs then

find <directory name> -name '*.pyc' -print0|xargs -0 -p <some number greater than 1> rm

This is unlikely to give you that much of a speed up however, due to the fact that you'll mostly be waiting on I/O.

| improve this answer | |
  • perfect ... thanks. It's the xargs I always forget – interstar Sep 7 '09 at 11:25
  • 2
    Just in case I have files with spaces in the names, I've gotten into the habit of always using -print0 and "xargs -0". – Paul Tomblin Sep 7 '09 at 11:28
  • You're entirely right, should have thought of that originally., edited to reflect that. – Cian Sep 7 '09 at 11:36
  • 4
    You can also directly use '-delete' instead of '-print0 | xargs -0 rm'. But that's true that this option isn't present in all version of 'find'. – rolaf Sep 7 '09 at 12:01

using the command find:

find /path/to/start -name '*.pyc' -exec rm -f {} \;
| improve this answer | |
  • That's too slow. Using xargs is faster, or if your version of find supports it, change the "\;" at the end to a "+". – Paused until further notice. Sep 7 '09 at 12:11
  • 1
    It may be a little slower--it runs "rm" once for each file instead of batching them--but it's the most portable way to do it. The OP didn't say what kind of unix he was using, and Solaris find still doesn't have the -print0 feature. – Kenster Sep 7 '09 at 13:49
  • 1
    +1, OP said unix not linux, this is the best portable solution. – theotherreceive Sep 7 '09 at 13:59
  • I think this solution is the only permitting to remove tons of files, if I am not wrong using xargs can leave into a command line too long error. +1, it is my choice since years too. – drAlberT Sep 7 '09 at 15:23
  • If you are using a makefile to build your project, you might want to add this in to the target "clean". – Tom Newton Sep 7 '09 at 16:01

cd to the start of the tree of directories then:

find . -name '*.pyc' |xargs rm -f

| improve this answer | |
  • It's not necessary to cd, just put the top directory in the find command (in place of "dot"). – Paused until further notice. Sep 7 '09 at 12:10
  • This doesn't handle spaces at all. – Cian Sep 7 '09 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.