Search code examples
bashreplacefile-renameuppercaselowercase

bash : change part of filename to lowercase


I need to rename a list of files changing any file extension to lowercase: ie: from My_TEST.ONE.two.Three.fOuR.FIve to My_TEST.one.two.three.four.five

At the moment the way I've found is this one

#!/bin/bash

sourcefilename="My_TEST.ONE.two.Three.fOuR.FIve"
newfilename=""
for word in $(echo $sourcefilename | tr '.' '\n'); do
        if [ -z "$newfilename" ]; then
                newfilename="$word"
        else
                newfilename="$newfilename.$(echo $word | tr [:upper:] [:lower:])"
        fi
done

Is there a better (and maybe elegant) approach?


Solution

  • Use bash Parameter Expansion features.

    fileName='My_TEST.ONE.two.Three.fOuR.FIve'
    first="${fileName%%.*}"
    rest="${fileName#*.}"
    echo mv -v "${fileName}" "${first}.${rest,,[A-Z]}"