Workflow: Bulk File Renaming with sed

Posted on 01/18/2009 @ 02:48AM

Even in this user-friendly, GUI-dominated world, the command line can still rock. Besides being always present (on Linux or OS X at least), there's so much slickness one can achieve if you know the right commands and how to use them.

Here's a quick example for renaming a bunch of files at once, something I've had to do about a zillion times:

ls | sed 's/\(.*\)\.png/mv \1\.png \1-on\.png/' | sh

For those that don't know, the sed, the "stream editor" command allows you to take in a bunch of text from a stream, do stuff with it, and send it back out to another stream.

In this case, I had a bunch of rollover images which I wanted to add the suffix "-on" to. So in the above command, we take the output of ls (a bunch of filenames), and send it to sed using a pipe ( | ). From there, sed replaces each file name with the appropriate mv command to rename the file. Lastly, the output is piped back out to sh to be executed.

If you just wanted to test the output before executing it, you could type:

ls | sed 's/\(.*\)\.png/mv \1\.png \1-on\.png/'

...and the generated commands will be output, but not executed.