Lowercase Filenames with Bash on Mac OS X

February 4th, 2010, filed under Apple, General

Have you ever thought about what name to give to a certain file? No? Well…I did, and so did alot of other people as well. Using a proper way to mange your files will reduce clutter and greatly improve the time it takes to find a document. Even Microsoft has thought about it!

When saving files to my hard drive I’d like the filenames to be in lowercase. This is even more important when you are using a *NIX-based operating system. However, I do not like renaming all files manually. So here’s a little bash script that will do this automatically:

#!/bin/sh

if [ -n "$1" ]; then
  let count=0
  while [ "$1" ]; do
    f="$1"
    shift
    if [ -f "$f" ]; then
      lc=`echo $f | awk '{print(tolower($0));}'`
      if [ "$lc" != "$f" ]; then
        mv "$f" "$lc"
        ((count++))
      fi
    fi
  done
  echo "Result: $count files have been changed."
else
  echo "Usage: lowerit file(s)"
fi

URL: An example showing the usage of the above script

Usage and examples

I’ve named this script lowerit and placed it in the /bin directory. You can read my previous post “Batch rename filename extension on a Mac” for more details about installing bash scripts on a Mac. Run this script by typing the following command:

~$: lowerit *

Using the asterisk (*) will lowercase all filenames in the current directory. It’s also possible to specify one single file, for example:

~$: lowerit Example.PHP

Combined with find you can also recursively change the filenames. The command to use should look something like this:

~$: find . -type f -exec lowerit {} \;

Off course this script can also be used to uppercase filenames as well. Just change awk print(tolower($0)) into awk print(toupper($0)) and your done!

One Response

To convert any var to lower…

var=${var,,}

see man bash :)

#!/bin/sh

if [ -n "$1" ]; then
  let count=0
  while [ "$1" ]; do
    f="$1"
    shift
    if [ -f "$f" ]; then
      lc=${f,,}
      if [ "$lc" != "$f" ]; then
        mv "$f" "$lc"
        ((count++))
      fi
    fi
  done
  echo "Result: $count files have been changed."
else
  echo "Usage: lowerit file(s)"
fi
Posted by

Have your say

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

You must be logged in to post a comment.