Leaderboard ad

3.31.2015

Converting Lowercase Text to Uppercase Text

Question sent in by Mr. Fisher.

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.  To change text from lowercase to uppercase with echo, you can use tr like so:

[savona@putor ~]$ echo ok | tr [:lower:] [:upper:]
OK

 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:

[savona@putor 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

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

[savona@putor tmp]$ me=savona
[savona@putor tmp]$ echo $me
savona
[savona@putor tmp]$ echo $me | tr [:lower:] [:upper:]
SAVONA

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

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:

[savona@putor ~]$ me=savona
[savona@putor ~]$ echo $me
savona
[savona@putor ~]$ echo ${me^^}
SAVONA

Or to convert to lowercase:

[savona@putor ~]$ echo $newme
SAVONA
[savona@putor ~]$ 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:

[vonas@putor ~]$ echo $me
savona
[vonas@putor ~]$ 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.

No comments:

Post a Comment