tr
Quick Reference
Command Name:
tr
Category:
text processing
Platform:
linux
Basic Usage:
Common Use Cases
- 1
Text translation
Translate or delete characters in text data
- 2
Text processing
Manipulate text data in pipelines and scripts
- 3
Data cleaning
Clean and sanitize text data
- 4
Scripting
Use in shell scripts to process text data programmatically
Syntax
tr [OPTION]... SET1 [SET2]
Options
Option | Description |
---|---|
-c, --complement | Use the complement of SET1 |
-d, --delete | Delete characters in SET1, do not translate |
-s, --squeeze-repeats | Replace each sequence of a repeated character in SET1 with a single occurrence of that character |
-t, --truncate-set1 | First truncate SET1 to length of SET2 |
--help | Display a help message and exit |
--version | Output version information and exit |
Examples
How to Use These Examples
The examples below show common ways to use the tr
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
Basic Examples:
echo "Hello World" | tr 'a-z' 'A-Z'
Converts lowercase letters to uppercase. This translates every character in the first set (lowercase a-z) to the corresponding character in the second set (uppercase A-Z).
echo "Hello World" | tr -d ' '
Deletes all spaces from the input. The -d option tells tr to delete any characters that are in the specified set, in this case, a space character.
echo "Hello World" | tr -s ' '
Squeezes multiple spaces into a single space. The -s option replaces repeated occurrences of a character in the input with a single occurrence of that character.
cat file.txt | tr '\n' ' '
Replaces newlines with spaces, effectively converting a multi-line file to a single line. This is useful for joining lines in a text file.
Advanced Examples:
echo "Hello 123 World 456" | tr -d '[:digit:]'
Deletes all digits from the input. This uses POSIX character classes, which are predefined sets of characters. [:digit:] represents all numeric digits.
echo "hello world" | tr '[:lower:]' '[:upper:]'
Converts lowercase letters to uppercase using POSIX character classes. This is similar to the first example but uses the predefined classes which makes it more readable and portable.