Home » Unix command and scripts » tr command in Unix

tr command in Unix

In this article, we will be discussing the use cases of the tr  Unix command with examples.

tr command

tr is used to  Translate characters.

Syntax
tr [-c] [-d] [-s] [string1] [string2]
-cComplement the set of characters specified by string1.
-dDelete all occurrences of input characters that are specified by string1.
-sReplace instances of repeated characters with a single character.
string1First string or character to be changed.
String2Second-string or character to change the string1.

How to convert lower case to upper case

We can use the tr command without 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 the -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

See also  Writing loop statement in Unix shell scripting with examples

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

Also Read
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 in Unix : 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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top