Sunday, May 29, 2011

Shell script to translate uppercase text to lowercase

Bookmark and Share

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 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 slightly lengthy 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

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 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


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. (Comments will be moderated.)

 




Technology