May 24, 2009

Bluk rename files in Linux

Today one of my friend asked me to bulk rename all files in a folder. He had a collection of songs named randomly with no extension. He also wanted to add the extension, mp3 in all files(Yes, he was sure about the encoding)
I opened a terminal in that folder and executed the following command.
NUM=1
for SONG in ./*
do
mv $SONG song$NUM.mp3
let NUM=NUM+1
done

So lets peek what the above script does:
  1. Defined a variable NUM and initialized it with 1.
  2. Defined a foreach loop. Here for each files in current path the for loop is executed.
  3. Rename(move) the file $SONG to song<num>.mp3
  4. Increase the value of variable NUM by 1.
  5. end. ;)
So if you want to rename in a different fashion you can hack the line mv $SONG song$NUM.mp3 in any way you like. But Remember the second argument to the mv command must vary for each loop, otherwise you will end up deleting all files except the last one.

3 comments:

Anonymous said...

i guess there is a quick command 'rename' for bulk renaming the files in linux.

SATA said...

Thanx. I was unaware of that.

Jadu Saikia said...

Yea, rename is a real useful one

http://unstableme.blogspot.com/2008/09/bash-rename-command-rename-multiple.html