Translating Characters
Problem
You need to convert one character to another in all of your text.
Solution
Use the tr command to translate one character to another. For example:
$ tr ';' ',' <be.fore >af.ter
Discussion
In its simplest form, a tr command replaces occurrences of the first (and only) character of the first argument with the first (and only) character of the second argument.
In the example solution, we redirected input from the file named be.fore and sent the output into the file named af.ter and we translated all occurrences of a semicolon into a comma.
Why do we use the single quotes around the semicolon and the comma? Well, a semicolon has special meaning to bash, so if we didn’t quote it bash would break our command into two commands, resulting in an error. The comma has no special meaning, but we quote it out of habit to avoid any special meaning we may have forgotten about—i.e., it’s safer always to use the quotes, then we never forget to use them when we need them.
The tr command can do more that one translation at a time by putting the several characters to be translated in the first argument and their corresponding resultant characters in the second argument. Just remember, it’s a one-for-one substitution. For example:
$ tr ';:.!?' ',' <other.punct >commas.all
will translate all occurrences of the punctuation symbols of semicolon, colon, period, exclamation point and question mark to commas. Since the second argument is shorter than the first, its last (and here, its only) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access