Linux Unix TR Command

the tr command stands for 'translate characters'. It is used to replace or delete characters.

tr command structure:

tr [OPTION] SET1 [SET2]

To learn how to use the tr command, let's create a simple file named 'cousins.txt' using the cat command in a terminal window :

cat > cousins.txt << EOF
Luka    m     14
Mathias m     11
Jules   m     11
Maxime  m      9
Eloise  f      5
Thibaud m      3
Nina    f     11
Zoe     f     15
Gaspard m      6 
EOF

To submit "cousins.txt" to the tr command you can proceed in two ways refer to the Unix Command page:

cat cousins.txt | tr [OPTION] SET1 [SET2]

tr [OPTION] SET1 [SET2] < cousins.txt

Learning from examples

Reminder : for more details on predefined class refer to the Regular Expressions page

How to convert a specific class of characters:

To convert lower case alphabetic characters to upper case alphabetic characters:

tr [:lower:] [:upper:] < cousins.txt
LUKA    M     14
MATHIAS M     11
JULES   M     11
MAXIME  M      9
ELOISE  F      5
THIBAUD M      3
NINA    F     11
ZOE     F     15
GASPARD M      6 

or either:

tr a-z A-Z < cousins.txt
LUKA    M     14
MATHIAS M     11
JULES   M     11
MAXIME  M      9
ELOISE  F      5
THIBAUD M      3
NINA    F     11
ZOE     F     15
GASPARD M      6 

How to replace each white-space with a semi column character:

tr [:blank:] ';' < cousins.txt
Luka;;;;m;;;;;14
Mathias;m;;;;;11
Jules;;;m;;;;;11
Maxime;;m;;;;;;9
Eloise;;f;;;;;;5
Thibaud;m;;;;;;3
Nina;;;;f;;;;;11
Zoe;;;;;f;;;;;15
Gaspard;m;;;;;;6;

How to remove repetition of replacement using -s (Only the first replacement occurs):

tr -s [:blank:] ';' < cousins.txt 
Luka;m;14
Mathias;m;11
Jules;m;11
Maxime;m;9
Eloise;f;5
Thibaud;m;3
Nina;f;11
Zoe;f;15
Gaspard;m;6;

How to convert multiple continuous spaces with a single space :

tr -s [:blank:] ' ' < cousins.txt
Luka m 14
Mathias m 11
Jules m 11
Maxime m 9
Eloise f 5
Thibaud m 3
Nina f 11
Zoe f 15
Gaspard m 6 

How to delete specified characters using -d option :

tr -d 'a,k' < cousins.txt
Lu    m     14
Mthis m     11
Jules   m     11
Mxime  m      9
Eloise  f      5
Thibud m      3
Nin    f     11
Zoe     f     15
Gsprd m      6 

How to remove all digits :

tr -d [:digit:] < cousins.txt
Luka    m     
Mathias m     
Jules   m     
Maxime  m      
Eloise  f      
Thibaud m      
Nina    f     
Zoe     f     
Gaspard m       

How to remove the complement using -c option

tr -cd [:digit:] < cousins.txt
14111195311156