Thursday, December 01, 2005

Unix/Linux Lesson: Executing a command on many files


I had to look this up for the third time in my Linux experience, so I decided to write it down this time. It's often necessary to run the same command on many files. There are various ways of doing this, depending on the situation. There's the bash shell's globbing (aka wildcards), of course. But if the files are in a directory tree instead of a single directory, the find command combined with xargs is the way to go.


The normal command is:

  find [options] | xargs command

This works great, usually. It fails when there are spaces in any filename or directory name. To get around this, use the following:
  find [options] -print0 | xargs -0 command

This makes sure that the command gets each filename as a single parameter on its command line, even if the filenames have spaces in them.

No comments: