Linux 'tr' Command – Detailed Guide
Introduction
The 'tr' command stands for translate or transform. It is used to modify text from standard input
(stdin) by replacing, deleting, or squeezing characters.
Syntax
Basic syntax of tr command:
tr [options] 'set1' 'set2'
Example 1: Replace Characters
Replace all occurrences of one character with another.
echo "hello world" | tr 'o' '0'
Example 2: Convert Lowercase to Uppercase
Convert all lowercase letters to uppercase.
echo "linux" | tr 'a-z' 'A-Z'
Example 3: Convert Uppercase to Lowercase
Convert uppercase letters to lowercase.
echo "HELLO" | tr 'A-Z' 'a-z'
Example 4: Delete Characters (-d)
Remove specific characters from input.
echo "hello123" | tr -d '0-9'
Example 5: Replace Spaces with New Lines
Convert spaces into new lines (useful in pipelines).
echo "this is linux" | tr ' ' '\n'
Example 6: Remove Repeated Characters (-s)
Squeeze repeated characters into a single occurrence.
echo "heyyy" | tr -s 'y'
Real World Pipeline Example
Break words, sort them, and count frequency.
tr ' ' '\n' < [Link] | sort | uniq -c
Key Points
- Works on characters, not words. - Uses standard input (stdin). - Commonly used with pipes. - Very
useful with sort and uniq.
Definition (For Exams)
The 'tr' command is used to translate, delete, or squeeze characters from standard input.