tr

tr — "translate" — works on text one character at a time. It can replace characters with other characters, remove characters, or collapse runs of a character into one.

tr [options] set1 [set2]

tr reads standard input and writes standard output — it has no file arguments, so it always sits in a pipeline.

$ tr 'a-z' 'A-Z' < notes.txt        # lower-case to upper-case
$ tr -d ' ' < spaced.txt            # delete every space
$ tr -s ' ' < padded.txt            # collapse runs of spaces to one

The three jobs #

What tr does depends on the options and how many sets you give it.

  • Translate — give two sets. Each character in set1 is replaced by the character at the same position in set2. tr 'abc' 'xyz' turns every a into x, b into y, c into z.
  • Delete (-d) — give one set. Every character in set1 is removed.
  • Squeeze (-s) — each run of a repeated character that appears in the relevant set is collapsed to a single occurrence.

-d and -s can be combined: delete one set of characters, then squeeze another.

Writing a set #

A set is a string of characters, with a few shorthands:

NotationMeans
a-zA range — every character from a to z.
[:alpha:], [:digit:], [:space:], …A named character class.
[=c=]An equivalence class — every character that sorts the same as c.
[c*n]The character c repeated n times — for padding a set to a length.
\n, \t, \\, \NNNEscapes — newline, tab, backslash, an octal byte.

Options #

OptionEffect
-d, --deleteDelete the characters in set1 instead of translating.
-s, --squeeze-repeatsCollapse each run of a repeated character listed in the last set into one.
-c, -C, --complementOperate on the complement of set1 — every character it does not list.
-t, --truncate-set1Before translating, shorten set1 to the length of set2, rather than reusing set2's last character to cover the surplus.

Exit status #

CodeMeaning
0Success.
1A usage error — the wrong number of sets, or a malformed set.

Edit this page