11

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

3 Answers 3

28

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.

3
  • 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". Sep 7, 2009 at 11:28
  • You're entirely right, should have thought of that originally., edited to reflect that.
    – Cian
    Sep 7, 2009 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, 2009 at 12:01
6

using the command find:

find /path/to/start -name '*.pyc' -exec rm -f {} \;
5
  • That's too slow. Using xargs is faster, or if your version of find supports it, change the "\;" at the end to a "+". Sep 7, 2009 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, 2009 at 13:49
  • 1
    +1, OP said unix not linux, this is the best portable solution. Sep 7, 2009 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, 2009 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, 2009 at 16:01
1

cd to the start of the tree of directories then:

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

2
  • It's not necessary to cd, just put the top directory in the find command (in place of "dot"). Sep 7, 2009 at 12:10
  • This doesn't handle spaces at all.
    – Cian
    Sep 7, 2009 at 14:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .