Friday, March 6, 2009

Batch Renaming music files with single digit track numbers, to prepend with a 0, with a Bash script.

So, you have a collection of music... say... 120GB of flac, ripped from CDs.

This collection is important to you, and took you a while to rip. You don't want to do it again.

You chose a filename schema $artistname/$albumname/$trackname - $songname.$fileextension

You like this schema, and its organized well, but one problem. Tracks 1 - 9 for each album have a single digit track number, but tracks 10 and up are two.

Some music players and programs view track 10 and 11 and on before tracks 1 - 9. There has to be a simple way to rename these files to have two digit filenames.

There is. There are programs out there that rename files based on the id3 tag, but lets say you don't want to bother with that, you just want to do a simple batch rename. A one line bash command will do the trick:

for file in [1-9]' '*; do mv "$file" 0"$file"; done

As I am new to bash scripting I wanted to figure out how to do this, and it took a full 15 minutes to figure out how bash escapes characters. It will evaluate shell variables inside double quotes, but not single quotes. The above one line script finds all files that start with a number from 1 through 9, and are immediately followed by a space. Conveniently, my 120GB of flac has a lot of these, and no other non-music files are there.

I saved the above to a script, zero_prepend.sh, chmod u+x zero_prepend.sh, and ./zero_prepend.sh within the directory that needs to be renamed.

I have to do that once on each album though. Let me figure out how to do this recursively on my entire collection.

1 comment:

  1. Excellent post. I just tried it and for me I had to replace the apostrophe's (the thing on the key w/ the quotation, left of the enter key) with back ticks (the thing to the left of the 1 key). It worked for what I was trying to do, though. Thank you.

    ReplyDelete