Batch Lowercase on the Mac OS X CLI
Posted May 31st, 2005 @ 09:20pm by Erik J. Barzeski
In a bash prompt:
for filename in * # Traverse all files in directory. do fname=`basename $filename` n=`echo $fname | tr A-Z a-z` # Change name to lowercase. if [ "$fname" != "$n" ] # Rename only files not already lowercase. then mv $fname $n fi done
Thanks, Aaron.
Posted 31 May 2005 at 9:23pm #
I found the answer in the advanced BASH scripting guide. They list two answers, the first one is the one I initially sent Erik. The second one was right below it and supports filenames with spaces/newlines in it.
for filename in * # Not necessary to use basename,
# since "*" won't return any file containing "/".
do n=`echo "$filename/" | tr '[:upper:]' '[:lower:]'`
# POSIX char set notation.
# Slash added so that trailing newlines are not
# removed by command substitution.
# Variable substitution:
n=${n%/} # Removes trailing slash, added above, from filename.
[[ $filename == $n ]] || mv "$filename" "$n"
# Checks if filename already lowercase.
done
Posted 31 May 2005 at 10:54pm #
For those who are not terminal inclined, I would recommend the excellent R-Name which can do this and much, much more. (I am not in any way connected to the author, just a fan of his software.)
Posted 31 May 2005 at 11:53pm #
Automater is pretty good for writing basic file rename scripts, and you can store them in the Finder's contextual menu. Not much use for the CLI, but otherwise pretty decent.
Posted 01 Jun 2005 at 7:09pm #
I use a (*GASP*) perl script. It's not very robust, but it works for what I use it for...
#!/usr/local/bin/perl
foreach (@ARGV) { rename $_, "\L$_\E"; }
Posted 02 Jun 2005 at 9:08pm #
There's actually a bug in the original script. The basename call will have odd effects. A more flexible approach is to make it a function in the shell. You can just put this in your .profile:
tolc () {
for f in $*; do
lc=$(echo "$f" | tr A-Z a-z)
[ "$lc" == "$f" ] || mv "$f" "$lc"
done
}
There are some advantages to this version. Namely it handles files with embedded spaces in the filename correctly and you can control what to run it on.
usage: tolc files ...
So things like:
tolc A*.jpg
or
tolc *.DAT
Will all work as expected. (I didn't test this, so if it barfs, let me know and I'll tweak it)