The tr command replaces (or deletes) individual characters from its input and passes the result to its output. For example, if you wanted to replace lowercase e with uppercase E, or all lowercase letters with uppercase letters, you could use the following command lines:

[email protected]:~ > cat file red elephant, red wine blue mango red albatross [email protected]:~ > cat file|tr e E rEd ElEphant, rEd winE bluE mango rEd albatross [email protected]:~ > cat file|tr a-z A-Z RED ELEPHANT, RED WINE BLUE MANGO RED ALBATROSS

However, for this example, it is probably better to do the following:

[email protected]:~ > cat file | tr [:lower:] [:upper:]

This has the same effect as the previous example, but does the right thing if we include accented characters in our file. For example:

[email protected]:~ > echo 'éléphant' |tr a-z A-Z éLéPHANT

[email protected]:~ > echo 'éléphant' |tr [:lower:] [:upper:] ÉLÉPHANT

[email protected]:~ > cat file |tr a-z mnopqrstuvwxyzabcdefghijkl dqp qxqbtmzf, dqp iuzq nxgq ymzsa dqp mxnmfdaee

Here, the tr command performs the simple rot13 cipher on the lowercase letters — each letter is moved forward 13 places in the alphabet. Repeating the command restores the original text.

With the option -d, tr simply removes the characters that are listed:

[email protected]:~ > cat file | tr -d abcde r Iphnt, r win lu mngo r Itross

With the option -s, tr removes repeats of the characters that are listed:

[email protected]:~ > cat repeats aaabcd abbbcd abcccd abcddd [email protected]:~ > cat repeats|tr -s ab abcd abcd abcccd abcddd

Repeated a's and b's have been lost.

| f - - r Exactly how the range of characters in the preceding examples is interpreted may depend on the locale, in other words the language settings in the current environment.

Was this article helpful?

0 0

Post a comment