tr command in Linux with 10 Examples

Written by: Bobbin Zachariah   |   Last updated: August 2, 2022

The tr command, which stands for translate, is a Linux tool that can translate, squeeze, or delete characters supplied from the standard input (STDIN) and output the results to your terminal screen, which is the standard output (STDOUT).

The tr command allows you to perform useful operations such as converting lowercase characters to uppercase characters, uppercase characters to lowercase characters, character replacing, and deleting characters. It is usually used in conjunction with other commands via piping.

This tutorial will teach you how to use the tr command effectively by using practical examples and detailed explanations of the most common options

Syntax

The syntax for the tr is pretty straightforward.

 $ tr [OPTION]... SET1 [SET2]

A breakdown of the syntax:

  • tr - the Linux tr command itself
  • OPTIONS - various Linux tr switches you can use to modify it's behavior.
  • SET1 and SET2 - the tr command accepts two sets of characters that must be the same length. It replaces characters from the first set (SET1) with characters from the second set (SET2). To put it another way, it replaces the characters in the first set with the characters in the second set.

What does tr command do in Shell?

Always keep in mind that the two sets that tr accepts must be of equal length. A SET is essentially a string of characters, including special characters that have been escaped with a backslash.

Let's take a look at a quick example of replacing characters or letters in standard input (STDIN) by mapping the characters to be replaced (SET1) with the characters that will replace them (SET2).

$ echo "Linux is so amazing, that I can't live without it :d." | tr "abcd" "ABCD"

From the command each occurrence of 'a' in the standard input is replaced with A, b with B, c with C and so on.

Output:

Linux is so AmAzing, thAt I CAn't live without it :D.

To define characters sets you also make use of character ranges. For instance, instead of writing:

$ echo "Linux is so amazing, that I can't live without it :d." | tr "abcd" "ABCD"

you can use the ranges as shown below and still get the same output:

$ echo "Linux is so amazing, that I can't live without it :d." | tr "a-d" "A-D"

Now that you understand the fundamentals of the tr command, let's look at some of the available options.

The -c option

The -c, -C, or—complement options change the behavior of tr to use the complement of SET1. In other words, it will replace all characters not found in SET1. In the following example, all characters except "GNU" are replaced with the very last character from the second set:

$ echo "GNULinux" | tr -c "GNU" "abc"

Output:

GNUcccccc 

If you look closely at the output above, you will notice that one more extra character has been replaced. This is due to the echo command printing an invisible single newline character n, which is replaced with c. Use the -n option with the echo command to echo a string without a newline as shown on the following command.

$ echo -n "GNULinux" | tr -c "GNU" "abc"

Here we have used the -n option and as expected the extra character 'c' has been removed.

Output:

GNUccccc 

The -d option

The -d (—delete) option tells tr to remove the characters listed in SET1. If you only want to delete characters without squeezing them, you should only specify one set as clearly shown in following example.

The following command will remove the /, L, i, n,u and x characters:

$ echo "GNU/Linux" | tr -d "/Linux" 

Output:

GNU

It should be noted that character sets are case sensitive, so attempting to delete a lowercase case letter by specifying its corresponding uppercase case letter will not work.

The -s option

The -s option The -s (--squeeze-repeats) option replaces each series of a repeated character that is in the last SET with a single instance of the repeated character.

$ echo "Linux----is---awesome" | tr -s "-"

Output:

Linux-is-awesome

When SET2 is used, the character sequence specified in SET1 is replaced with SET2.

$ echo "Linux----is---awesome" | tr -s "-" "~"

Output:

Linux~is~awesome

The -t option

The -t (--truncate-set1) option instructs tr to first truncate SET1 to the length of SET2 before proceeding.

The default behavior is for tr to reuse the last character of SET2 if SET1 is greater than SET2. Here's an illustration:

$ echo -n "GNULinux" | tr  "lix" "LQ"           

Output:

GNULQnuQ 

The output clearly shows that the SET1 character s matches the last character of SET2, which is Q:

Let us now try the same command with the -t option and see what happens:

$ echo -n "GNULinux" | tr -t  "lix" "LQ"

Output:

GNULQnux

As shown in the preceding example, the character at the end of the SET1 is removed. The character 'li,' which has the same length as SET2, replaces SET1.

Combining the options we discovered

The tr command, like any other Linux command, allows you to combine/tackle its options. For instance, the following command removes all numbers except characters:

$ echo "Linux is 56 years old" | tr -cd "a-zA-Z "

Output:

Linux is  years old

tr Command Examples in Linux

Let's now look at some 10 practical examples of how to use the tr command.

1. Deleting repeated characters

We can use the -s option to squeeze a character that is repeating to make it a single character. This option is especially useful when you want to squeeze multiple continuous spaces characters into a single character. The following example clearly shows that:

$ echo "Linux    is awesome,   I'm in love with it." | tr -s " " 

Output:

Linux is awesome, I'm in love with it.

From the above example you can clearly see the multiple spaces have been translated to single space.

Instead of using the space character in our character SET for squeezing repeating characters, we can also make use of character classes and still get the same results.

$ echo "Linux    is awesome,   I'm in love with it." | tr -s "[:space:]" 

2. Delete specific characters

Using the -d option, you can delete characters you specify. tr command deletes every instance of the "-" character in the following example:

$ echo "Some- people- are- afraid- to- use -the Linux -System." | tr -d "-"

Output:

Some people are afraid to use the Linux System.

3. Delete all the digits

You can also use the -d option to remove any numbers or digits from your text.

$ echo "Some people are afraid to use the Linux System. 2022" | tr -d "[:digit:]" 

Output:

Some people are afraid to use the Linux System.

Instead of using character classes you can use number character range.

$ echo "Some people are afraid to use the Linux System. 2022" | tr -d "0-9" 

4. Case conversion

The tr command is frequently used to convert lowercase letters to uppercase letters or the opposite.. The character class [:lower:] matches all lowercase characters, while the character class [:upper:] matches all uppercase characters.

The following will transform characters from upper case to lower case.

$ echo "Some people are afraid to use the Linux System." | tr "[:lower:]" "[:upper:]"

Output:

SOME PEOPLE ARE AFRAID TO USE THE LINUX SYSTEM.

Alternatively, you can also use character range in place of the character classes.

$ echo "Some people are afraid to use the Linux System." | tr "a-z" "A-Z"

5. Removing non alphanumerical characters

We can combine the complement option (-c) with the delete option (-d) to delete all non-alphanumerical characters.

The following command will delete all non-alphanumerical characters.

$ echo "I: have- been@ using# Linux for 12 years." | tr -cd "[:alnum:]"

Output:

IhavebeenusingLinuxfor12years   

6. Print each word on a single line

The $PATH variable is an environmental variable that contains a list of directories separated by a colon that instructs the shell where to look for executable files when you type a command.

So if you're having trouble reading the directories in the $PATH variable, you can make use the tr command to replace the colons with the newline characters so each directory is displayed on a single line.

$ echo $PATH | tr ":" "\n"                                             
Output
/usr/local/sbin
/usr/sbin
/sbin
/usr/local/bin
/usr/bin
/bin
/usr/local/games
/usr/games

The preceding example will replace all the semicolon in our path variable with the newline characters.

7. Remove all non-numeric characters

The -c option instructs tr to use the complement in the SET given. In this example, we want to remove all of the letters and only keep the phone number.

$ echo "Call me at +449883200382" | tr -cd "[:digit:]"

Output:

449883200382   

This is very useful if you want to extract phone numbers or employee IDs from text files.

8. Remove Newline Characters

Assume you have a text file containing data that looks like this, and you want to remove the newlines and put the words on a single line separated by spaces..

I
love
Linux

To achieve that, you can redirect you file contents to the tr command as shown on the below command.

$ tr "\n" " " < file.txt 

Output:

I love Linux   

The preceding command will replace each newline character in a text file with a space.

9. Put each word in a new line

As a system administrator, you may be given employee names on single lines separated by spaces, and you may want to put each name on a single line for easy readability.

The command below will assist you in accomplishing this by dividing a sentence into multiple lines, with each word on its own line.

$ echo "john james kay  fredrick george" | tr "[:space:]" "\n"

Output:

john
james
kay
fredrick
george

10. Convert a forward slash (/) to a hyphens (-).

As a system administrator, you may be tasked with changing the date formats from yyyy/mm/dd to the new format yyyy-mm-dd.

Here's an example of converting a forward slash (/) to a hyphen (-) and then appending the data to a file for storage.

$ tr "/" "-" < old-date-format.txt > new-date-format.txt

About The Author

Bobbin Zachariah

Bobbin Zachariah

Bobbin Zachariah is an experienced Linux engineer who has been supporting infrastructure for many companies. He specializes in Shell scripting, AWS Cloud, JavaScript, and Nodejs. He has qualified Master’s degree in computer science. He holds Red Hat Certified Engineer (RHCE) certification and RedHat Enable Sysadmin.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment