tr Command in Linux
Overview
In this article, we will explore the tr command in Linux, a useful tool for translating, deleting, and squeezing characters from standard input, writing the result to standard output. The tr command is primarily used for text processing and manipulation, including translating, deleting, and replacing characters.
Linux tr Command Syntax
The syntax for the tr command is as follows:
Where:
- OPTION: The command-line flags and options used to modify the behavior of the tr command.
- SET1: The first set of characters used as input for the tr command.
- SET2: The second set of characters used as input for the tr command, typically used for translation purposes.
tr Command Options:
- -c, -C, --complement: Use the complement of SET1.
- -d, --delete: Delete characters in SET1.
- -s, --squeeze-repeats: Replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character.
- -t, --truncate-set1: First truncate SET1 to the length of SET2.
Example Usages
-
Translate lowercase to uppercase:
Output:
Explanation: The tr command translates all lowercase letters to their corresponding uppercase letters.
-
Delete specified characters:
Output:
Explanation: The tr command deletes all vowels (aeiou) from the input string.
Tips
-
Use single quotes around character sets to prevent shell interpretation.
-
tr can be used to remove non-printable characters from a file.
Advanced Use Cases of tr Command in Linux
-
Squeeze repeated characters:
Output:
Explanation: The tr command squeezes repeated spaces into a single space.
-
Translate and delete characters:
Output:
Explanation: The tr command first translates all uppercase letters to lowercase, and then deletes all digits.
-
Complement character set:
Output:
Explanation: The tr command deletes all characters not in the complement of the specified character set (a-zA-Z and space), effectively removing all non-alphabetic characters and spaces.
Conclusion
-
tr command is used for translating, deleting, and squeezing characters in a given text.
-
tr command can be combined with other commands using pipes.
-
tr command options include complementing, deleting, squeezing, and truncating character sets.