Skip to content

The tr command

The tr command changes or deletes characters in text from a pipe…

The tr command changes or deletes characters in text from a pipe: tr a-z A-Z makes it upper case, and tr -d deletes characters.

Taught in Intermediate, lesson 21

A practice shell in your browser that behaves like bash on Linux for these commands. Nothing you type leaves the page.

Usage

tr [-c] [-s] SET1 SET2
tr -d [-c] SET1

Translate or delete characters. Reads text from a pipe (or < file) and changes characters: each character of SET1 becomes the character in the same place in SET2. With -d it deletes the characters in SET1, and with -s it squeezes repeats of a character into one. Sets can use ranges such as a-z and classes such as [:upper:], [:lower:], [:digit:] and [:space:]. tr never takes a file name: send the file in with < or a pipe.

How to use tr

Upper or lower case

tr a-z A-Z < names.txt
LEO
AVA
MIA
AVA
LEO
AVA
ZAC
echo "Hello World" | tr "[:upper:]" "[:lower:]"
hello world

Replace one character with another

tr , ";" < data.csv
name;score
Ava;82
Leo;91
Mia;77

Delete characters: tr -d

tr -d "0-9" < app.log
: INFO started
: ERROR disk not found
: INFO retrying
: error: timeout
: INFO ready
: WARN slow request

Squeeze repeats: tr -s

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

Put each word on its own line

Turn spaces into new lines, then count with sort and uniq.

cat report.txt | tr " " "\n"
Quarterly
report
Sales
went
up
4%.

Options

-d, --deletedelete the characters in SET1
-s, --squeeze-repeatsreplace a run of the same character with one
-c, --complementuse every character that is NOT in SET1

More examples

tr a-z A-Z < fruit.txt
Upper case
PEAR
APPLE
PEAR
FIG
APPLE
PEAR
tr , "\t" < data.csv
Commas to tabs
name	score
Ava	82
Leo	91
Mia	77
tr -d 0-9 < app.log
Delete every digit
: INFO started
: ERROR disk not found
: INFO retrying
: error: timeout
: INFO ready
: WARN slow request
echo "too many spaces" | tr -s " "
Squeeze runs of spaces into one
too many spaces

Questions about tr

Why does tr say "extra operand" when I give it a file?

tr reads only from standard input. Send the file in with <, as in tr a-z A-Z < file.txt, or pipe it: cat file.txt | tr a-z A-Z.

Learn it step by step

Every everyday command on one page, to print or keep open: the Linux commands cheat sheet.