Shell script to translate uppercase text to lowercase

While shell scripting on UNIX/LINUX/SOLARIS/AIX et cetera, it is often a requirement to translate uppercase characters to lowercase characters.

It can be a user input or contents of a file that one might be processing using shell scripting.

Below one-liner uses ‘tr’ CLI to translate uppercase characters to lowercase characters.

# strName=”TECHSUTRAM IN LOWERCASE"
# echo $strName| tr ‘[A-Z]’ ‘[a-z]’
techsutram in lowercase

Simple, isn’t it? However, there is a catch. The ‘tr’ CLI used for translation might not work on all UNIX flavors to convert all uppercase characters to lowercase.

The trick is to use a slightly longer form of ‘tr’ to make translation almost portable to other UNIX flavors. So above code can be rewritten as,

# strName=”TECHSUTRAM IN LOWERCASE"
# echo $strName| tr ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’ ‘abcdefghijklmnopqrstuvwxyz’
techsutram in lowercase

The same mechanism works for translating lowercase characters to uppercase characters as below.

# strName=”techsutram in uppercase"
# echo $strName| tr  ‘abcdefghijklmnopqrstuvwxyz’ ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
TECHSUTRAM IN UPPERCASE
 

That’s it. This trick has worked for me.
Do you know any other common method that can be used to translate uppercase characters to lowercase characters? If YES then let everyone know in the comments below.

 

You may also be interested in,
+ Converting .wav to .mp3 file format in Linux
+ MD5SUM for all files in directory
+ FTP file upload using shell script on LINUX/UNIX

Note: We at TechSutram take our ethics very seriously. More information about it can be found here.
Mandar Pise Opinions expressed by techsutram contributors are their own. More details

Mandar is a seasoned software professional for more than a decade. He is Cloud, AI, IoT, Blockchain and Fintech enthusiast. He writes to benefit others from his experiences. His overall goal is to help people learn about the Cloud, AI, IoT, Blockchain and Fintech and the effects they will have economically and socially in the future.

2 comments:

  1. What if i want to convert the string " MyNamE" where each letter gets converted to the opposite case instead of the string as a whole ??

    The converted output for the above given string should be " mYnAMe ".

    ReplyDelete
  2. Thanks for the tip. How to convert string to initcap (first letter of the word should be in uppercase and rest of the letter should be in lower case).
    tr command example in unix

    ReplyDelete

    Your valuable comments are welcome. (Moderated)