tr
tr
The tr
command in Unix and Linux is used to translate or delete characters from the standard input and write the result to the standard output. It is commonly used for simple text processing tasks such as changing case, deleting characters, and squeezing repeated characters.
Basic Usage
The basic syntax for the tr
command is:
options
: Command-line options to control the behavior oftr
.SET1
: The set of characters to be replaced or deleted.SET2
: The set of characters to replace those inSET1
(if specified).
Examples
Translating Characters
To translate lowercase characters to uppercase:
Output:
This command translates all lowercase letters in the input string to uppercase.
Deleting Characters
To delete specific characters:
Output:
This command deletes all digits from the input string.
Squeezing Repeated Characters
To squeeze (remove repeated) characters:
Output:
This command squeezes repeated occurrences of characters 'a', 'b', and 'c' in the input string.
Options
-d
Option: Delete Characters
The -d
option is used to delete characters specified in SET1
.
This command deletes all digits from the input string.
-s
Option: Squeeze Characters
The -s
option is used to replace each sequence of repeated characters listed in SET1
with a single occurrence of that character.
Output:
This command replaces each sequence of spaces with a single space.
Practical Use Cases
Changing Case
To change the case of characters in a text:
Output:
This command converts all uppercase letters to lowercase.
Removing Unwanted Characters
To remove unwanted characters, such as non-printable characters:
This command removes all non-printable characters from file.txt
.
Replacing Characters
To replace specific characters with another set of characters:
Output:
This command replaces all occurrences of 'o' with '0' in the input string.
Summary
The tr
command is a versatile and powerful tool for simple text processing in Unix and Linux environments. Its ability to translate, delete, and squeeze characters makes it ideal for tasks such as changing case, removing unwanted characters, and condensing repeated characters. Understanding its options and use cases can significantly enhance your text manipulation capabilities.
help
breakdown
Last updated