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.txtTranslate 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'
312This 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 caseQuote 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: 5550100A frequent use is removing Windows carriage returns:
$ tr -d '\r' < windows.txt > unix.txtSqueeze with -s
-s collapses a run of the same listed character into one.
$ echo "too many spaces" | tr -s ' '
too many spacesComplement with -c
-c means "every character not in the set".
$ echo "id 42, room 7" | tr -cd '0-9\n'
427This 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
cPractise in the streams and text lab.
Try it
- Run
echo $PATH | tr ':' '\n'. - Uppercase your user name with
whoami | tr '[:lower:]' '[:upper:]'. - Remove all vowels from a sentence with
tr -d 'aeiou'. - Squeeze repeated letters in
aaabbbwithtr -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.