Introduction
The tr (translate) command is an essential tool in the Linux command line that allows translating, deleting, and squeezing characters from a text input. Although its syntax is simple, its power lies in the ability to process data streams without needing to write complex scripts.
Basic Syntax
The general form of tr is:
tr [OPTIONS] SET1 [SET2]
Where SET1 defines the set of characters to search for and SET2 (optional) the replacement set. If SET2 is omitted, tr deletes the characters in SET1.
Character Translation
One of the most common applications is changing uppercase to lowercase or vice versa.
echo 'hola Mundo' | tr 'a-z' 'A-Z'
This command converts all text to uppercase, yielding HOLA MUNDO. Likewise, to convert to lowercase:
echo 'HOLA Mundo' | tr 'A-Z' 'a-z'
Character Deletion
If only SET1 is provided, tr deletes those characters from the input.
echo 'hola2023!' | tr -d '0-9'
The result will be hola!. Several types of characters can be deleted by combining ranges:
echo 'hola, mundo; 2023.' | tr -d ' ,;'
This removes spaces, commas, and semicolons, leaving holamundo2023.
Compressing Repeated Characters
With the -s (squeeze) option, repeated sequences of the same character can be reduced to a single occurrence.
echo 'aaabbbccc' | tr -s 'ab'
The result is abc, since the sequences of a and b are compressed.
Practical Use Cases
- Clean log files by removing line numbers:
cat log.txt | tr -d '0-9' - Convert Windows line endings (\r\n) to Unix format:
tr -d '\r' < archivo.txt - Generate random passwords using only uppercase letters and numbers:
cat /dev/urandom | tr -dc 'A-Z0-9' | head -c12 - Remove comments from a shell script (assuming they start with #):
tr -d '#' < script.sh
Tips and Tricks
- Use
--helpto see all available options. - Remember that sets can include character classes such as
[:alpha:],[:digit:]or[:space:]
This post is also available in ESPAÑOL.