Q: I am just learning shell scripting (bash in particular) and I need to convert some text into all uppercase.  I was told to use sed, but this seems foreign to me.

A: You can do it right in bash with the tr command.  The tr stands for “translate” and allows you to do some wonderful text manipulation.  The following quick tip will show you multiple methods to change the case of strings. To learn more in-depth information about the tr command read “Linux tr Command Usage and Examples“.

To change text from lowercase to uppercase with echo, you can use tr like so:

[[email protected] ~]$ echo ok | tr [:lower:] [:upper:]
OK

Change Case of Whole Text File

You can use tr in many different ways by piping input into or out of tr, or using redirection.  For example, if you wanted to change all text in a file to uppercase, you can just run tr against the file, like so:

[[email protected] tmp]$ tr '[:lower:]' '[:upper:]' < testfile
OK, THIS IS A TEST FILE
CREATED IN ALL LOWERCASE
TO BE CONVERTED BY
REDIRECTING INTO TR COMMAND

If you want to save the file in all caps simply cat the file, pipe it through tr, then redirect it to a file like so:

cat testfile | tr '[:lower:]' '[:upper:]' > output.txt

Converting Case of a Variable

If you are using this in a script, you can also convert strings stored in a variable with tr.

[[email protected] tmp]$ me=savona
[[email protected] tmp]$ echo $me
savona
[[email protected] tmp]$ echo $me | tr [:lower:] [:upper:]
SAVONA

NOTE: You can reverse [:lower:] and [:upper:] to switch the text from uppercase to lowercase.

Using Bash Case-Conversion Pairs

In newer versions of bash (Bash Version 4+) there is a feature that allows for more elegant case conversions called the case-conversion pair. 

Using the same example as above, we can convert a variable using the case-conversion pair built into bash like so:

[[email protected] ~]$ me=savona
[[email protected] ~]$ echo $me
savona
[[email protected] ~]$ echo ${me^^}
SAVONA

Or to convert to lowercase:

[[email protected] ~]$ echo $newme
SAVONA
[[email protected] ~]$ echo ${newme,,}
savona

So to recap, it either ^^ to convert to uppercase, or ,, to convert to lowercase.

You can also convert just the first letter by using a single ^ or , like so:

[[email protected] ~]$ echo $me
savona
[[email protected] ~]$ echo ${me^}
Savona

This is a lot more elegant and easier to type, although it is not as versatile as the tr command.  For example, you can not convert a whole text file using this technique.

Conclusion

Here we covered a few ways to change the case of strings, complete files and variables. The tr command is a very powerful tool. You should read “Linux tr Command Usage and Examples” to learn more about this Interesting Utility.