Skip to content

tr

"The tr utility copies the standard input to the standard output with substitution or deletion of selected characters." - man tr

Examples

Interestingly, tr does not have any features to operate on files. It operates only on stdin. To use it on files you must use input redirection like tr .... < filename.txt or pipes like cat filename.txt | tr ...

Replace all non-letters with a carriage return

-s shrinks adjacent matches into a single match.

$ echo abcdefghijklmnopqrstuvwxyz | tr g-t '_'
abcdef______________uvwxyz
$ echo abcdefghijklmnopqrstuvwxyz | tr -c g-t '_'
______ghijklmnopqrst_______
$ echo abcdefghijklmnopqrstuvwxyz | tr -s g-t '_'
abcdef_uvwxyz
$ echo abcdefghijklmnopqrstuvwxyz | tr -cs g-t '_'
_ghijklmnopqrst_$

In Doug McIlroy's critique of Donald Knuth's unique word count finder, tr was used twice. Here's a somewhat modified version:

$ man tr | tr -cs A-Za-z '\n' | tr A-Z a-z | sort | uniq -c | sort -rn | head
  96 the
  45 in
  44 characters
  38 string
  30 of
  29 a
  25 to
  23 tr
  22 character
  21 is

See also

  • tr is often used with [cut](cut.md), though I prefer [awk](awk.md) most of the time.