tr command is mainly used to translate or delete characters in bash. tr is not a complex but useful command. We will look at various usage scenarios of tr in this tutorial.
Syntax
We will use the following syntax for tr
command.
tr [OPTION]... SET1 [SET2]
Help
Help can get with --help
parameter like below.
$ tr --help

Man
The manpage of tr can be also viewed below.
$ man tr

Convert Lowercase To Uppercase
One of the most popular usages of tr is converting texts from lowercase to uppercase.
$ tr [:lower:] [:upper:]

Convert Uppercase To Lowercase
Reverse application of Lowercase to uppercase is uppercase to lowercase. This can be implemented with the command below.
$ tr a-z A-Z
OR
$ tr [:upper:] [:lower:]

Translate Braces To Parenthesis
We can translate braces into parenthesis like below. This can be applied to other characters too.
$ tr '{}' '()'

Translate White-space To Tabs
White spaces can be expressed like below and translated to the tabs with the following command.
$ tr [:space:] '\t' < reverse_fruits.txt

Delete Specified Characters
Another useful feature is deleting specified characters from the given text. The character that will be deleted is specified with -d
parameter like below.
$ tr -d 'T'

Complement Characters
The filtering is another feature of tr. Only Specified characters can be printed like below. In this example, we will only print numbers or digits with the following command.
$ echo "My ip address is 192.168.1.1" | tr -cd [:digit:]

Remove All Non-printable Characters
Non-printable characters can be removed with the following command with-cd [:print:]
$ tr -cd [:print:] < reverse_fruits.txt

Join Multiple Line Into Single
The following command will translate line endings into spaces and make the whole multi-line text a single line text.
$ tr -s '\n' ' ' < reverse_fruits.txt

Expressions
All supported expressions can be found below.
CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in SET2, copies of CHAR until length of SET1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR
1 thought on “Linux tr Command Tutorial With Examples”