Friday, July 20, 2012
9:01 PM

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.

Example:



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

Example:



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 :



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.



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.

Example:

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

temp:





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:



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.



Using tr over a range of characters



Deleting repetitive characters




0 comments:

Post a Comment