Sunday, February 27, 2011

Scripting On The Fly: Renaming All Files In A Directory

OK, so I was downloading a flock of files from a particular website, and it insisted on using capital letters for filename extensions (.PDF, in this case).  Of course, capital letters are anathema to any old-school Unix guy, so I found myself with directory full of files with mixed-case names - what to do?  Well, this was a job for a one-shot, on-the-fly script entered from the command line.  The only "unusual" command I used was basename(1), which (when given a filename and a suffix) returns everything before said suffix.  So, from the command line:

wmorgan@galileo:~/docs/flyers$ ls | while read filen
>do
>mv $file `basename $filen .PDF`.pdf
>done
wmorgan@galileo:~/docs/flyers $

Et voila'!  A directory with dozens of files named "whatever.PDF" are now named "whatever.pdf".  I could have used tr(1) to translate from upper- to lower-case, but that would have been a bit more expensive; tr(1) checks every character in the input string, while basename(1) allows us to effectively ignore the case of everything before the specified suffix...

 

No comments: