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:
[savona@putor ~]$ 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:
[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
Converting Case of a Variable
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.
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:
[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:
[savona@putor ~]$ echo $me
savona
[savona@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.
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.
Join Our Newsletter
Categories
- Bash Scripting (17)
- Basic Commands (50)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (65)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)