Manipulating Strings in Linux with tr
In this tutorial, we’ll see how to manipulate strings using the tr in Linux.
Note that we’ve tested these commands using Bash, but should work on any POSIX-compliant terminal.
2. Lower Case to Upper Case
tr [OPTION]... SET1 [SET2]
Where SET1 and SET2 each represent a SET of characters and a parameter inside  means it’s optional. The tr command is normally combined with pipes in order to manipulate standard input and get a processed standard output.
In this case, let’s transform a string from lower case to upper case:
echo "Baeldung is in the top 10" | tr [a-z] [A-Z]
The output of the command will be:
BAELDUNG IS IN THE TOP 10
3. Translate Whitespaces to Tabs
echo "Baeldung is in the top 10" | tr [:space:] '\t'
And we’ll get the translated string:
Baeldung is in the top 10
4. Delete Characters
Suppose that we are using the Linux terminal, we have the string “Baeldung is in the top 10”, and we want to delete all the occurrences of the character “e”. We can easily do this by specifying the -d parameter and the character that we want to delete from the phrase:
echo "Baeldung is in the top 10" | tr -d 'e'
And our result is:
Baldung is in th top 10
In addition, we can delete multiple characters by putting them all in a single set. Let’s say that we want to remove all the vowels:
echo "Baeldung is in the top 10" | tr -d 'aeiou'
Let’s check the output:
Bldng s n th tp 10
Now, imagine we want to delete all the digits that appear in the phrase. We can do this by using the same -d parameter plus the references to the digits set:
echo "Baeldung is in the top 10" | tr -d [:digit:]
Once again, we can see the output of the command:
Baeldung is in the top
5. Complementing Sets
Let’s continue with the previous example of deleting the vowels. If, instead of deleting the vowels, we want to do the opposite – that is, the complementary operation – we just need to add the -c parameter and this will do the magic:
echo "Baeldung is in the top 10" | tr -cd 'aeiou'
Now the output will be the deletion of all characters except the vowels:
For more info, check out the tr man page online or by typing man tr in the terminal.