tr: To translate characters

The command “tr” can be used to translate/change or delete characters from the input.

By default tr takes two arguments, the first one being the set of characters to be searched for and the second argument being the set of characters to be replaced with . The default input is the standard input.


$ tr x y xyx yyy $

The command waits for user to enter a string and then hit the return key. In the above example on entering “xyx” the character x has been replaced by character y which was what was passed as arguments to the command.

We can also pass multiple characters as arguments and each characters will be considered separately and not as a string and each of the characters in argument1 will be replaced by the corresponding character in the argument2


$ tr xyz abc xyz abc x a y b z c

If the string length of argument1 is greater than that of argument2 then the last character of argument2 is applied to all the characters of argument1 that are after the string length of argument2.

Example :

$ tr xyz ab xyz abb x a y b z b

As we can see both y and z are replaced by b.

We can change this behavior by passing the option “-t” which will truncate the characters of first argument to the same as the length of argument2.

$ tr -t xyz a xyz ayz x a y y z z

Thus we can see, “y” and “z” both are not replaced by character.

The command can be applied on files by using the input redirection.


Let say we have a file,temp, with following contents


one 1 two 2 three 3 four 4

$ tr o O < temp One 1 twO 2 three 3 fOur 4 We can see that all o have been replaced with O. Instead of translating, we can delete characters too by passing the option “-d” . Example: $ tr -d [:digit:] < temp one two three four Thus we can see that all the digits in the file have been deleted. Other examples: We can user “tr” to convert all the characters in a file to upper case too. $ tr [:lower:] [:upper:] < temp ONE 1 TWO 2 THREE 3 FOUR 4 Using tr over a range of characters $ tr -d 1-3 < temp one two three four 4 Deleting repetitive characters $ tr -s e eeee e $

Related Blogs

    Tags: ,
    Copyright 2017. All rights reserved.

    Posted July 20, 2012 by Tux Think in category "Linux