GAURAV KUMAR

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
do
len="${#i}" ;
let len-=46
#echo "$len";
name="${i:0:len}" ;
#echo "$name"
mv "$i" "$name" ;
done

save it with name.sh and run "bash name.sh" 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
jungle.mpg.47IMRQGAGFWOA7GMLZTK3X6QFIGR4P4EKHDRHKI.dctmp
became Guns N' Roses - Welcome To The Jungle.mpg

Worked on ubuntu 10.10

2 comments:

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

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

    ReplyDelete