The tr Command

tr (translate) replaces or deletes characters. It's simple but surprisingly useful.

Basic Translation

Terminal
$echo 'hello' | tr 'a-z' 'A-Z'
HELLO
$echo 'HELLO' | tr 'A-Z' 'a-z'
hello

Convert lowercase to uppercase (or vice versa).

Replace Specific Characters

Terminal
$echo 'hello world' | tr ' ' '_'
hello_world
$echo 'a,b,c,d' | tr ',' '\n'
a b c d

Split to Lines

tr ',' '\n' is great for converting comma-separated values to one-per-line.

Delete Characters

Terminal
$echo 'Hello 123 World' | tr -d '0-9'
Hello World
$echo 'Hello World!' | tr -d '[:punct:]'
Hello World

-d deletes characters from the set.

Squeeze Repeats

Terminal
$echo 'hello world' | tr -s ' '
hello world
$echo 'aaabbbccc' | tr -s 'abc'
abc

-s (squeeze) replaces repeated characters with a single one.

Fix Multiple Spaces

tr -s ' ' is the quick fix for messy spacing in text files.

Character Classes

tr supports character classes:

ClassMatches
[:alpha:]Letters
[:digit:]Digits
[:alnum:]Letters + digits
[:space:]Whitespace
[:punct:]Punctuation
[:lower:]Lowercase
[:upper:]Uppercase
Terminal
$echo 'Hello123' | tr -d '[:digit:]'
Hello
$echo 'Hello World' | tr '[:lower:]' '[:upper:]'
HELLO WORLD

Complement

Terminal
$echo 'Hello123World' | tr -cd '[:digit:]'
123

-c complements the set (everything NOT in the set).

-cd '[:digit:]' = delete everything that's NOT a digit = keep only digits.

Real-World Examples

Convert DOS to Unix Line Endings

Terminal
$tr -d '\r' < dos_file.txt > unix_file.txt

Clean Up Whitespace

Terminal
$cat messy.txt | tr -s '[:space:]'
(single spaces only)

Extract Numbers

Terminal
$echo 'Order #12345 - Total: $99.99' | tr -cd '0-9\n'
123459999

Replace Spaces with Underscores in Filenames

hljs bash
echo "my file name.txt" | tr ' ' '_'
# my_file_name.txt
Knowledge Check

How do you remove all digits from text?

Key Takeaways

  • tr translates or deletes characters
  • tr 'a-z' 'A-Z' converts case
  • -d deletes characters
  • -s squeezes repeated characters
  • -c complements (inverts) the character set
  • Use character classes like [:digit:], [:alpha:]
  • tr only works with stdin (pipe to it)

Next: find and replace with sed.