Sunday, August 16, 2009

Renaming a bunch of files in one line

I recently wanted to rename a bunch of files. There is a one line command to do it. Lets say you have a bunch of files named old1.jpg ... old100.jpg. And you want to rename them as los-angeles-1.jpg .. los-angeles-100.jpg. This is how you do it on a mac shell:

ls old*.jpg | awk '{print $1 ," los-angeles-"substr($1,4)}'| xargs -n2 mv

This should do the trick. Here is an explanation:
The first part ls old*.jpg lists all the files.
The above is piped to awk, and we ask by awk '{print $1 ," los-angeles-"substr($1,4)}' to print the file name itself ($1 part) and " los-angeles-"substr($1,4) prints them as los-angeles-1.jpg and so on.
Finally, we pipe this output to xargs, with a -n2 flag which tells xargs that there are two inputs to mv.

Happy mv-ing.