BASH tr command

Dan picture Dan · Jun 22, 2012 · Viewed 47.1k times · Source

Id like to convert it to uppercase for the simple purpose of formatting so it will adhere to a future case statement. As I thought case statements are case sensitive.

I see all over the place the tr command used in concert with echo commands to give you immediate results such as:

echo "Enter in Location (i.e. SDD-134)"
read answer (user enters "cfg"

echo $answer | tr '[:lower:]' '[:upper:]'   which produced

cfg # first echo not upper?

echo $answer #echo it again and it is now upper...

CFG

Answer

ghoti picture ghoti · Jun 22, 2012

This version doesn't require bash, but uses a pipe:

read -p "Enter in Location (i.e. SDD-134) " answer
answer=$(echo "$answer" | tr '[:lower:]' '[:upper:]')
echo "$answer"

And if you're using bash and don't care about portability you can replace the second line with this:

answer="${answer^^}"

Check the "Parameter Expansion" section of bash's man page for details.