Skip to content

Linux Foundations / Find your way around Linux ยท Step 43 of 63

Lesson: tr (Translate)Switch
โ† Linux Foundations

Shell and files

tr (Translate)

Learn to replace, delete and squeeze characters in a stream with tr.

tr changes individual characters as text flows through it. It can translate, delete or squeeze them.

Input comes from stdin only

tr does not accept file names. Feed it with a pipe or with <.

$ echo "hello" | tr 'a-z' 'A-Z'
HELLO
$ tr 'a-z' 'A-Z' < notes.txt

Translate one set into another

The first character of set one maps to the first of set two, and so on.

$ echo "cab" | tr 'abc' '123'
312

This works on characters, not words. tr 'cat' 'dog' replaces every c with d, every a with o and every t with g, wherever they appear.

Character classes name whole groups:

$ echo "Mixed Case" | tr '[:upper:]' '[:lower:]'
mixed case

Quote the sets so the shell does not expand the brackets. GNU tr handles single bytes, so accented letters may not be converted.

Delete with -d

$ echo "phone: 555-0100" | tr -d '-'
phone: 5550100

A frequent use is removing Windows carriage returns:

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

Squeeze with -s

-s collapses a run of the same listed character into one.

$ echo "too    many   spaces" | tr -s ' '
too many spaces

Complement with -c

-c means "every character not in the set".

$ echo "id 42, room 7" | tr -cd '0-9\n'
427

This deletes everything except digits and newlines. Leave out \n and the final newline is removed as well.

One more use is putting each word on its own line:

$ echo "a b c" | tr ' ' '\n'
a
b
c

Practise in the streams and text lab.

Try it

  1. Run echo $PATH | tr ':' '\n'.
  2. Uppercase your user name with whoami | tr '[:lower:]' '[:upper:]'.
  3. Remove all vowels from a sentence with tr -d 'aeiou'.
  4. Squeeze repeated letters in aaabbb with tr -s 'ab'.

Check your understanding

tr (Translate)

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.