Objective: Convert the contents of a file or the contents of a shell string variable from lowercase to uppercase.
There are too many ways to do that. Let’s take a look at a few of them. Throughout this article, you can assume that the file “lowercase.txt
” is the input file and the file “uppercase.txt
” is the output file.
Lowercase to Uppercase with tr
The first method is to use the tr
command. The below command will read the text found in file lowercase.txt
, convert the text to upper case and write the output to file uppercase.txt
.
1 |
$ tr '[:lower:]' '[:upper:]' < lowercase.txt > uppercase.txt |
If the input is stored in a variable, use the echo
command and pipe the output to tr
command. So, if the variable $LCASE
has a string in lowercase, convert it using the syntax below.
1 |
$ echo $LCASE | tr '[:lower:]' '[:upper:]' |
Lowercase to Uppercase with awk
Use the following syntax to convert the contents of the file using awk
.
1 |
$ awk '{print toupper($0)}' < lowercase.txt > uppercase.txt |
To convert a string variable ($LCASE
) from lowercase to uppercase, use the following syntax.
1 |
$ echo $LCASE | awk '{print toupper($0)}' |
Lowercase to Uppercase with dd
Yes, the dd
command is also able to perform the case conversion. Perform the case conversion using the following syntax.
1 |
$ dd if=lowercase.txt of=uppercase.txt conv=ucase |
To convert a string variable, and print the result on the screen, use the following syntax.
1 |
$ echo $LCASE | dd conv=ucase 2> /dev/null |
Lowercase to Uppercase with sed
This works on GNU sed
only as it uses GNU sed
extension. Perform case conversion by using the following syntax.
1 |
$ sed -e 's/\(.*\)/\U\1/' lowercase.txt > uppercase.txt |
The ‘\1’ matches the whole line since the whole regular expression is within parenthesis. The special sequence ‘\U’ changes text to uppercase.
For a string variable containing lowercase characters, convert it to uppercase with sed
by using the following syntax.
1 |
$ echo "$LCASE" | sed -e 's/\(.*\)/\U\1/' |
Lowercase to Uppercase with Bash Shell
Bash shell allows case modification through parameter expansion. To change the string variable ($LCASE
) from lowercase to uppercase, use the following syntax.
1 |
$ echo "${LCASE^^}" |
The “^^
” expansion changes the characters to uppercase.