Renaming multiple files, specifically changing their case

Hey all,

I'm running a BASH shell and I was wondering if anyone knows a code to rename all the files in a directory. All I need to do is change the first character in the file from uppercase to lowercase and some of the files are already lowercase so they don't need to change.

-Thanks

 $ ruby -e 'Dir["*"].each{|x| File.rename(x,  x[0].downcase+x[1..-1]) if x[/^[A-Z]/]   }' 
1 Like

Using less exotic languages (*poke*) :

for file in * ; do
   newname="$(echo $file | cut -c 1 | tr 'a-z' 'A-Z')${file#?}"
   /bin/mv "$file" "$newname"
done

The cut extracts the first character from $file, and the tr transforms it into uppercase. The ${file#?} leaves behind all but the first character in the filename. Double-quotes are used in case the filename has funny characters or spaces.

1 Like

since you are using some bash syntax, why not do the "cutting" using bash ?

1 Like

My script doesn't nicely handle the case where the the file already has the proper name. In those cases, mv will complain about target and source being the same file. To prevent that, simply change the for:

for file in [a-z]* ;do

As far as a "pure" bash solution, I don't think one exists without writing a big case-Waac to handle lower - upper case conversion. Luckily, cut and tr are standard tools on every system. But it's pretty cool to see how ruby is apt for more than just web programming.

1 Like