Lesson 30: tr Command
In this lesson, you'll learn how to use the tr command to translate and delete characters from standard input in Linux.
redirectingtr (short for translate) is a useful command-line utility that translates and/or deletes characters from stdin input and writes to stdout. It is a useful program for manipulating text on the command line.
Let's discuss some useful tr command examples for its understanding.
tr Command Syntax
The syntax for running the tr command is as follows, where characters in SET1 are translated to characters in SET2.
$ tr [FLAGS] [SET1] [SET2]
tr Command Options
| Option | Description |
|---|---|
-d |
Delete characters in SET1 from the input |
-s |
Squeeze repeated characters in SET1 into a single character |
-c |
Use the complement of SET1 |
-t |
Truncate SET1 to the length of SET2 before translating |
1. Convert Lowercase to Uppercase
A simple tr command use case is to change all lowercase letters in the text to uppercase and vice versa, as shown below.
First, let's view the contents of the file:
$ cat linux.txt
linux is my life
linux has changed my life
linux is best and everthing to me..:)
Now, convert all lowercase letters to uppercase:
$ cat linux.txt | tr [:lower:] [:upper:]
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)
2. Convert Lowercase to Uppercase Using Character Range
Alternatively, you can use the following command to change all lowercase letters to uppercase using the character range notation:
$ cat linux.txt | tr [a-z] [A-Z]
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)