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 : Awk command in Unix or Linux is a powerful command for processing text. Learn about awk syntax, records, fields, line Separator with examples of awk in unix
sed command : sed command is a Stream Editor – works as a filter processing input line by line And here are 32 Useful sed command examples in Linux/Unix
grep command : Grep command Means – globally search regular expression.grep command in unix is used for searching text,regular expression across multiple files
windows grep equivalent: windows grep equivalent to search text: Find | findstr | power select-string. Detailed explanation with lots of example for easy understanding
tee command in Unix: Check out about tee command in Unix,what options are available, how to append file using tee command, how to write to multiple files
gzip and gunzip command in Linux