Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

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

First of all, let's see the synopsis of the command and how to use a predefined SET of the tool.

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

Another option that we can try with tr is translating all whitespace occurrences to tabs, continuing with the same example but a little bit tuned for this purpose:

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

We can also complement any of the sets that tr gives us.

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:

aeuiieo

6. Conclusion

In this quick tutorial, we've looked at how easy it is to manipulate strings using tr in a Bash shell.

For more info, check out the tr man page online or by typing man tr in the terminal.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of