Bash scripting: rename upper case file extensions to lower case

Posted by jason on Oct. 25, 2011, 10:18 p.m.
Tags: bash linux programming regex

I recently had one of my quick-and-dirty bash scripts broken because I wasn't expecting to receive a bunch of files named *.JPG as opposed to *.jpg. "Yay! I get to improve my bash script!" I thought to myself. Here's a script that will look at the files in the current directory and, if there are any upper case letters in the file extension, the file will be renamed to have the same extension but with lower case letters.

#!/bin/sh

FILES=$(ls -1)

for FILE in $FILES
do
    EXT=$(echo $FILE | awk -F . '{print $NF}')
    if [[ $EXT =~ [A-Z]{1,} ]]
    then
        BASE=${FILE%\.*}
        NEWEXT=$(echo $EXT | tr '[:upper:]' '[:lower:]')
        if [ ! -e $BASE.$NEWEXT ]
        then
            mv $FILE $BASE.$NEWEXT
        else
            echo "Could not rename $FILE to $BASE.$NEWEXT: $BASE.$NEWEXT already exists!"
        fi
    fi
done

exit 0

0 comments