Using the tr
Command
The tr
command, short for "translate", is a powerful tool used to translate or delete characters in a text stream. It's particularly useful for tasks like converting case, removing specific characters, or replacing one character with another.
Let's start with some basic tr
operations:
- Delete specific characters from a string:
echo 'hello labex' | tr -d 'olh'
This command will remove all occurrences of 'o', 'l', and 'h' from the input string. Here's what's happening:
echo 'hello labex'
outputs the text "hello labex"
- The
|
(pipe) symbol sends this output to the tr
command
tr -d 'olh'
tells tr
to delete (-d
) any 'o', 'l', or 'h' characters it finds
You should see e abex
as the output. Notice how all 'o', 'l', and 'h' characters have been removed.
- Remove duplicate characters:
echo 'hello' | tr -s 'l'
This command will squeeze (-s
) or remove duplicates of the letter 'l' in the input string. You should see helo
as the output.
echo 'balloon' | tr -s 'o'
You should see balon
as the output. The duplicate 'o' has been squeezed into a single 'o'.
- Convert text to uppercase:
echo 'hello labex' | tr '[:lower:]' '[:upper:]'
This command will convert all lowercase letters to uppercase. Here's what's happening:
'[:lower:]'
is a character class that represents all lowercase letters
'[:upper:]'
is a character class that represents all uppercase letters
- The command tells
tr
to replace any character in the first set with the corresponding character in the second set
You should see HELLO LABEX
as the output.
Try these commands and observe the output. Don't worry if you make a mistake â you can always run the command again. If you're curious about what might happen, try changing the input text or the characters in the tr
command.
For example, what do you think will happen if you run:
echo 'hello world' | tr 'ol' 'OL'
Try it out and see!
If you want to learn more about tr
, you can use man tr
to view its manual page. This will give you a comprehensive list of all options and uses for tr
. To exit the manual page, just press 'q'.
Remember, in Linux, most commands follow a similar structure: command [options] arguments
. Understanding this pattern will help you as you learn more commands.