Skip to content
C.W.K.
Stream
Lesson 05 of 10 · published

tr: Character Translation

~8 min · tr, character

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The lightest text tool

tr works on individual characters, not lines or words. Read stdin, translate or delete characters, write stdout. No regex, no fields. Just character mappings.

The four useful modes

  • tr 'a-z' 'A-Z' — translate set 1 to set 2 (1:1).
  • tr -d 'aeiou' — delete every vowel.
  • tr -s '\n' — squeeze runs of newlines into one.
  • tr -c 'a-zA-Z' '_' — complement: replace every non-letter with underscore.

Special character classes

tr understands [:upper:], [:lower:], [:digit:], [:space:], [:punct:]. tr -d '[:punct:]' nukes punctuation; tr '[:upper:]' '[:lower:]' is the locale-aware lowercase.

What tr can't do

It can't replace strings — only characters. tr 'foo' 'bar' doesn't change foo into bar; it maps f→b, o→a, o→r per character. For string-level replacement, use sed.

Daily uses

  • Strip Windows line endings: tr -d '\r' < in.txt > out.txt
  • Tab-to-space: tr '\t' ' '
  • Random uppercase: echo 'hello' | tr a-z A-Z
  • Compress whitespace: tr -s '[:space:]' ' '

Separate byte cleanup from Unicode processing

tr is simple for bounded ASCII work such as removing CR bytes. Korean, emoji, and combining characters can span bytes and code points and require a Unicode-aware tool.

Before squeezing all whitespace

tr -s '[:space:]' ' ' can collapse newlines and tabs with spaces, destroying record boundaries. Decide whether line structure may be discarded and preserve the source.

Code

Common one-liners·bash
# Word-frequency the lazy way (lowercase + split into words)
tr 'A-Z' 'a-z' < article.txt \
  | tr -cs 'a-z' '\n'        \  # words on their own lines
  | sort | uniq -c | sort -rn | head

External links

Exercise

Strip CR from a file: tr -d '\r' < windows.txt > unix.txt. Lowercase any text: cat ~/.zshrc | tr A-Z a-z | head. Word-frequency on a README: tr A-Z a-z < README.md | tr -cs a-z '\n' | sort | uniq -c | sort -rn | head.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.