Linux tr

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Linux tr

The command 'tr' stands for 'translate'. It is used to translate, like from lowercase to uppercase and vice versa or new lines into spaces.

Syntax:

command | tr <'old'> <'new'>

Change Case

The 'tr' command can change case.

Syntax:

command | tr <'old'> <'new'> 

Example:

cat exm.txt | tr 'prcu' 'PRCU' 

Linux tr Filters1

Look at the above snapshot, all p,r,c,u are converted into upprecase P,R,C,U.

Remove New Lines

To write all the lines into a single line we have to translate all new lines into spaces.

Syntax:

command | tr <' '> <' '> 

Example:

  1. cat exm.txt | tr ' ' ' '  

Linux tr Filters2


tr Options

  • tr -s : The 'tr -s' command squeezes the occurence of multiple characters into one.

Syntax:

ommand | tr -s <'letter'> 

Example:

  1. cat jtp.txt | tr -s 'l'  
  2.     cat spaces.txt | tr -s ' '  
  3.    

Linux tr Filters3

Look at the above snapshot, command "cat jtp.txt | tr -s 'l'" has squeezed all the letters 'l' into one and command "cat spaces.txt | tr -s ' '" has squeezed all the spaces into single space.

  • tr rot13: This command encrypts the text. It is case-sensitive.

Example:

  1. cat exm.txt | tr 'a-z' 'nopqrstuvwxyzabcdefghijklm'  
  2.     cat exm.txt | tr 'a-z' 'n-za-m' 

Linux tr Filters4

Look at the above snapshot, all the letters are encrypted according to the command. But letter 'A' and 'M' are not encrypted as they are in upper case.

  • tr -d: The 'tr -d' command is used to delete characters.

Syntax:

  1. command | tr -d <letter>  

Example:

  1. cat exm.txt | tr -d o   

Linux tr Filters5

Look at the above snapshot, all the 'o' letters are deleted from the file 'exm.txt'.