Objective: Convert the contents of a file or the contents of a shell string variable from uppercase to lowercase.
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 “uppercase.txt
” is the input file and the file “lowercase.txt
” is the output file.
Uppercase to Lowercase with tr
The first method is to use the tr
command. The below command will read the text found in file uppercase.txt
, convert the text to lower case and write the output to file lowercase.txt
.
1 |
$ tr '[:upper:]' '[:lower:]' < uppercase.txt > lowercase.txt |
If the input is stored in a variable, use the echo
command and pipe the output to tr
command. So, if the variable $UCASE
has a string in uppercase, convert it using the syntax below.
1 |
$ echo $UCASE | tr '[:upper:]' '[:lower:]' |
Uppercase to Lowercase with awk
Use the following syntax to convert the contents of the file using awk
.
1 |
$ awk '{print tolower($0)}' < uppercase.txt > lowercase.txt |
To convert a string variable ($UCASE
) from uppercase to lowercase, use the following syntax.
1 |
$ echo $UCASE | awk '{print tolower($0)}' |
Uppercase to Lowercase 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=uppercase.txt of=lowercase.txt conv=lcase |
To convert a string variable, and print the result on the screen, use the following syntax.
1 |
$ echo $UCASE | dd conv=lcase 2> /dev/null |
Uppercase to Lowercase 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/\(.*\)/\L\1/' uppercase.txt > lowercase.txt |
The ‘\1’ matches the whole line since the whole regular expression is within parenthesis. The special sequence ‘\L’ changes text to lowercase.
For a string variable containing uppercase characters, convert it to lowercase with sed
by using the following syntax.
1 |
$ echo "$UCASE" | sed -e 's/\(.*\)/\L\1/' |