Sunday, April 24, 2011

Rename multiple files with bash script

Hi there,
Recently I came up with a problem related to filename of downloaded files.In my college I use DC(Direct Connect) client to download files from other peers.Recently I downloaded a large number of music videos which remained in temporary directory and did not move to music directory.Although It downloaded completely, It remained in temporary directory and hence name of files was in the format "filename.(avi/mpg/flv etc.).(some chars).dctmp". So I had to rename them.Definitely, I couldn't do it manually as there were more than 1000 files.Hence I tried to write a bash script for renaming all of them at once.
Initially I tried to store the filename as "*.*.dctmp" in which I would trim the "*.dctmp" part.Hence the remaining part would the desired filename(with proper externsion).But storing the filename like that did not work out.
Then I saw that in temp files, there is a common pattern that before "dctmp" extension, there are exactly 39 chars. Then I tried a different method of trimming filename which is explained below with code.

code :

for i in *.dctmp
len="${#i}" ;
let len-=46
#echo "$len";
name="${i:0:len}" ;
#echo "$name"
mv "$i" "$name" ;

save it with and run "bash" on terminal.The script should be run in the same directory in which temp files are present.

e.g. Guns N' Roses - Welcome To The
became Guns N' Roses - Welcome To The Jungle.mpg

Worked on ubuntu 10.10


  1. I use Windows Vista. Ubuntu is so slow.

  2. Lol. People call Ubuntu slow. What douchebags :)