December 4, 2024

Many commands in Linux are obscure but extremely useful if you get to know them. The yes command is one, and another one which this article will cover is the tr command.

The tr command is short for translate, but instead of translating languages, it translates or deletes input characters and symbols to something else. Say, for example, you would like to replace spaces from an output with a new line character so that each output is on a new line, the tr command can do that quickly and easily. 

Or you would like to replace a delimiter with a tab, space, or a new line. The tr command can do all of those too.

Here is how to use it:

Translate delimiter colon to newline:

Consider a long output like below. It seems squished and crowded.

default ouput from reading the /etc/passwd file

Here is how the tr command makes it a lot more readable:


cat /etc/passwd | head | tr : “\n”
use the tr command to replace colon with a newline character

What it does is take the input character (delimiter colon : ) and translate it to a new line character. So, the output will each appear on a separate line.

Translate delimiter colon to tabs:

Let’s make this original output a lot easier to read by adding tabs next to the entries. So, the tr command in this case would look like:


cat /etc/passwd | head | tr : ”\t”

It will translate the : character from the output to a tab. So, the filtered output would be:

use the tr command to replace delimiter with a tab

Pretty neat. Besides translating characters to newlines and tabs, the tr command can also be used to translate to a backspace (\b).

use the tr command to replace delimiter with a backspace for deleting characters

So, when this is used, you would find that the output would have one character deleted from it after running the tr command. 

You can use the tr command with files as well as various commands. 

default output of the uname command

Translate space to newline

For example, to have the output of the uname command appear on a different line, use the tr command as follows:


uname -a | tr “ “ “\n”
use the tr command to have the output from uname command appear on a new line each

Note that, unlike the other inputs like delimiters, you would need to enclose space within quotes when providing them as an input to the tr command.

This will translate the spaces to a new line character, which would make the output of the uname command appear on a new line. Pretty neat stuff.

The man page for tr

As with all Linux commands, you can dig in deep about what tr can do with the man page:


man tr
The man page for tr command

Feel free to use various parameters to see how it can help you with modifying output as needed.

use the v parameter in tr command to produce nested ouput

All done.

By admin

Related Post