Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

The Linux tr Command

Translate, delete and squeeze characters in text with tr.

How-To Guides2 min read9 screenshots

What is tr

tr (translate) changes or removes characters in text that comes from standard input. It does not take file names, so you use it with a pipe or with <.

Syntax

tr [OPTION] SET1 [SET2]

Options:

  • -c complements SET1, which means it works on all the characters not in the set.
  • -d deletes the characters in SET1.
  • -s squeezes repeated characters in SET1 into a single one.
  • -t truncates SET1 to the length of SET2.

Read the manual:

man tr
The tr manual page

Example 1: Change the case

Lower case to upper case:

echo "Hi, I am a technical writer" | tr 'a-z' 'A-Z'
Converting lower case letters to upper case

Upper case to lower case:

echo "HI, WELCOME TO THE KNOWLEDGE BASE" | tr 'A-Z' 'a-z'
Converting upper case letters to lower case

You can also use the classes: tr '[:lower:]' '[:upper:]'.

Example 2: Save the result in a file

echo "HI, WELCOME TO THE KNOWLEDGE BASE" | tr ' ' '\n' > words.txt
Redirecting the output of tr to a file

This replaces each space with a new line and writes the result to words.txt.

Example 3: Replace one character

Replace a comma with a semicolon:

echo "one,two,three" | tr ',' ';'
Replacing a specific character

Output: one;two;three

Example 4: Squeeze repeated characters

echo "hello     world" | tr -s ' '
Removing repeated characters

Output: hello world

Example 5: Delete characters

Delete a specific character:

echo "hello world" | tr -d 'l'
Removing a specific character

Output: heo word

Delete all digits:

echo "abc123def456" | tr -d '0-9'
Removing all digits

Output: abcdef

Example 6: Use the complement

Keep only the digits and delete everything else:

echo "abc123def456" | tr -cd '0-9'
Complementing a set

Output: 123456

Other uses

Remove Windows line endings from a file:

tr -d '\r' < windows.txt > unix.txt

Make a random password of 16 letters and digits:

tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 16; echo

Quick recap

  • tr 'a-z' 'A-Z' changes case, tr -d deletes, tr -s squeezes, tr -c complements.
  • tr reads only from standard input.