Untitled Document
tr Command

tr - command stands for translating characters . The tr ( translate) filter manipulates individual characters in a line .More specifically , it translates characters using one or two compact expression . The syntax for tr is :

   tr options expression1 expression2 standard input        

tr takes input only from standard input ; it doesn't take a filename as argument . Let's use to replace , ( comma ) with tilde ( ~ )

Example 1 - Basic Example

Run below tr command

   tr ',' '~' < emp.csv  

Example 2 - Basic Example suing variables

We can define the two expressions as two seprate variables and then evaluate them in double quotes :

   exp1=',' ; exp2='~'
   tr "$exp1" "$exp2" < emp.csv     

Example 3 - Changing case of text

Since tr doesn't except a file as argument , the input has to be redirected from a fille . The following sequence changes the case of the lines from lower to upper .

   cat emp.csv | tr '[a-z]' '[A-Z]' 

Example 4 - Deleting Characters ( -d )

The file emp.csv is comma separated and the date formatted in readable form with a / . To convert this date into ddmmyyyy format we have to delete / . The followinf command does this for us .

   tr -d '/' < emp.csv  

Example 5 - Compressing Multiple Consecutive Characters ( -s )

We can remove all the redundant spaces with the -s ( squeeze) option , which squeezes multiple consecutive occurences of its argumnet to a single character . We can then have compressed output with lines in free format .

   tr -s ' ' < emp.csv  

Example 6 - Complementing Values of Expression ( -c )

The -c ( complement )option complements the set of characters in the expression . Thus, to delete all characters except , ( comma) . Thus to delete all characters except , ( comma) we can combine the -d and -c option

   tr -cd ',' < emp.csv  
Untitled Document