Wednesday, July 18, 2007

Adding a leading zero to a file name

I often find this necessary when trying to get audiobook files to automatically sort correctly. For example, files from chapter one are named "1-01 Book Name" and "1-02 Book Name", but files from chapter 11 are named "11-01 Book Name" and "11-02 Book Name." In the current case, they were in all kinds of strangely named subdirectories, so first I had to copy them all into a single directory. (I did this in Ubuntu Feisty, but it should work in most flavors of Linux and OSX and Cygwin (for Windows users )):

find . -type f -name "*mp3" -exec mv {} ~/bookdir/ \;

Next I moved the ones that already were correctly formatted. There's a more elegant way to do this, selecting files that have digits in the first two places, but my case was so simple that I used the dumb way:

mv 10* 2dig
mv 11* 2dig

Finally we get to the actual renaming, using substitution syntax.

rename 's//0/' *.mp3

The part in the single quotes means substitute anything with an initial zero. In english it would be add an initial zero.

Now move the correctly named files back into your directory, and voila:

mv 2dig/* .

Some wizard could do all this with a single command, but I'm not that wizard.

No comments: