AI Hints
Home›Linux Tutorial›Changing Text
Linux · Lesson 49 of 120

tr: Translating Characters

Swap or delete characters.

⏱ 2 min read▶ Video at 1:02:52🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Sometimes you need to change text, not just search it. Turn lowercase into capitals, swap one character for another, or delete characters you don't want. The smallest tool for that is TR, short for translate.

tr: Translating Characters
From the video: tr: Translating Characters
  • Change text, not just search
  • Swap or delete characters
  • tr: translate

Swapping characters

TR reads from a pipe, and swaps characters. Here, every lowercase letter becomes a capital. In the second example, every comma becomes a space, which turns a CSV line into plain words.

Terminal
echo "hello linux" | tr a-z A-Z
HELLO LINUX
head -n 2 team.csv | tr "," " "
name role city
sam developer London

Deleting characters

Dash D deletes characters. Here we delete every digit from a sentence. And dash S squeezes repeats, so many spaces in a row become just one. Handy for cleaning up messy text.

Terminal
echo "Room 101, floor 3" | tr -d 0-9
Room , floor
echo "too    many     spaces" | tr -s " "
too many spaces

What tr can and cannot do

TR works on single characters, not whole words. It can't turn cat into dog. And it only reads from a pipe or input, never from a file name directly. For replacing whole words, we need a stronger tool, called sed.

keyvalue
a-z A-Zchange case
-ddelete characters
-ssqueeze repeats
Whole words?use sed instead

Summary

TR translates, deletes, or squeezes characters, reading from a pipe. Next, sed, for finding and replacing words.

Key takeaways
  • tr a-z A-Z
  • tr -d
  • tr -s
Next up: sed: Find and Replace — s/old/new/