In this article, we will be discussing the useful cases of tr unix command with examples.
tr is used to Translate characters.
tr [-c] [-d] [-s] [string1] [string2]
|-c||Complement the set of characters specified by string1.|
|-d||Delete all occurrences of input characters that are specified by string1.|
|-s||Replace instances of repeated characters with a single character.|
|string1||First string or character to be changed.|
|String2||Second string or character to change the string1.|
How to convert lower case to upper case
We can use tr command with out option -d,-c and -s for that
$ echo $ORACLE_SID| tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ TECH $ echo $ORACLE_SID| tr [a-z] [A-Z] TECH $ echo $ORACLE_SID| tr [:lower:] [:upper:] TECH $ echo "good boy" | tr good bad bddd bdy
How to Delete specified characters using -d option
tr can also be used to remove particular characters using -d option.
$ echo $ORACLE_SID TECH $ echo $ORACLE_SID| tr -d ‘T’ ECH $echo "good boy" | tr -d "g" ood boy
How to use option -s to convert repeated occurrence of character into single character
tr ‘[A-Z]' ‘[a-z]' <1.txt | tr -cs 'a-z' '\n' | sort
What this does is pass the contents of 1.txt to the tr command to translate uppercase letters to lowercase; the output from that is piped to another tr command that turns everything except lowercase letters into line breaks (effectively putting each word on a separate line); that’s piped to sort which puts the lines (words) in alphabetical order
How to use option -c with tr
-c can be used to find the complement of string1.
For example, to remove all characters except digits, you can use the following
$ echo " My id is MQ123452" | tr -cd [:digit:] 123452
I hope you like this content on tr command in Unix
awk command : Complete guide on awk command in Unix with lot of examples
sed command : A good overview of sed command and difference between awk and sed and much more
grep command : A lot of grep command with options
windows grep equivalent: Grep equivalent in window OS
tee command in Unix
gzip and gunzip command in Linux