Sunday, April 19, 2009

change file names in *nix

I was looking for a easy way to change the names of a set of files this Friday and learned a trick, yes on *nix based operating systems with a bash shell. Sorry if you are windows, you should be able to do this on mac though.
Here is what I wanted to do - I wanted to rename a list of 100 files. example: rename Sun001,png to sunny_001.png For a lot of reasons, I want the file names to be all lower case all the time - its just my style. I do not not know if there are other easy ways to do it, maybe tools but I wanted it to do the shell way. I split the whole thing into two steps - 1) convert all the file names to lower case 2) replace sun with sunny_ I looked around for help and here is how I did it:

1. lower case all the names
for x in `ls`; do mv $x `echo tr '[A-Z]' '[a-z]'`; done
the above command converts all the file names to lower case. "tr" is translate command which is used to translate characters. "tr '[A-Z]' '[a-z]'" translates all the upper case characters to lowercase. Yes, "tr" accepts a range of characters.

2. replace "sun" with "sunny"
for x in `ls`; do mv $x `echo $x | sed "s/sun/sunny_/g"`; done
As you can see above I used sed for search and replace in the file names. sed is stream editor and it is used to edit a stream, the stream could be a file or could be stdin or even could be piped from the output of other command (as you see above). "s///options" is something common in all editors at nix world.
So thats all I have, hope it was helpful. Please feel free to add more tips if you have.