35.11 Hacking on Characters with trThe tr command is a character translation filter, reading standard input (13.1 ) and either deleting specific characters or substituting one character for another. The most common use of tr is to change each character in one string to the corresponding character in a second string. (A string of consecutive ASCII (51.3 ) characters can be represented as a hyphen-separated range.) For example, the command:
will convert all uppercase characters in file to the equivalent lowercase characters. The result is printed on standard output. In the System V version of tr
, square brackets must surround any
range of characters.
That is, you have to say: If you aren't sure which version you have, here's a test.
The Berkeley version converts the input % There's one place you don't have to worry about the difference between the two versions: when you're converting one range to another range, and both ranges have the same number of characters. For example, this command works in both versions: $ The Berkeley tr
will convert a The System V version also has a nice feature: the syntax
As described in article 30.22 , this translation (and the reverse) can be useful from within vi for translating a string. You can also delete specific characters. The -d option deletes from the input each occurrence of one or more characters specified in a string (special characters should be placed within quotation marks to protect them from the shell). For instance, the following command passes to standard output the contents of file with all punctuation deleted (and is a great exercise in shell quoting (8.14 ) ): $ The -s (squeeze ) option of tr removes multiple consecutive occurrences of the same character in the second argument. For example, the command: $ will print on standard output a copy of file in which multiple spaces in sequence have been replaced with a single space. We've also found tr useful when converting documents created on other systems for use under UNIX. For example, as described in article 1.5 , tr can be used to change the carriage returns at the end of each line in a Macintosh text file into the newline UNIX expects. tr allows you to specify characters as octal values by preceding the value with a backslash, so the command: $ does the trick. The command: $ will remove the carriage return from the carriage return/newline pair that a PC file uses as a line terminator. (This command is also handy for removing the excess carriage returns from a file created with script (51.5 ) .) Article 29.10 uses tr to split sentences into words. - , |
|