Skip to content

tr command in Linux (transforms text)

The tr command in Linux replaces one variable with another specified one. This command does not work directly with files, so it should be used with the standard output of another command, with the pipe conductor.

The tr command can swap characters from the search variable to the swap variable, but the number of characters must be the same in both.

The most common options are:

  • -d: Delete occurrences of the search variable;
  • -s: Suppress repeated occurrences of the search variable;

Take the example with the grocery list, where tr is used to change all lowercase letters to uppercase letters:

$ cat list
rice
meat
lettuce
Tomato
$ tr [a-z] [A-Z] < list RICE MEAT LETTUCE TOMATO

The tr command can be useful for transforming spaces for TABS into a file:

$ cat file | tr ': [space] :'' t' > out.txt

You can also fix text by removing spaces:

$ cat domains www. certificacaolinux.com.br www. kernel.org www. nic .br
$ cat domains | tr -d '' www.certificacaolinux.com.br www.kernel.org www.nic.br

It can also remove repeated characters:

$ cat domains www.certificacaolinux... com.br www.kernel.org www.nic.br
$ cat domains | tr -s'. '

www.certificacaolinux.com.br www.kernel.org www.nic.br It can also be used to replace Return “ n” with a comma:

$ cat domains | tr -s'. '| tr' n' ',' www.certificacaolinux.com.br, www.kernel.org, www.nic.br,

You can also do the opposite by transforming a file with items separated by commas into lines:

$ cat file
Read Organa, General, Resistance
Luke Skywalker, Jedi, Resistance
$ cat file | tr ',' ' n'
Read Organa
Gen
stamina
Luke Skywalker
Jedi

Resistance Watch a video of how this command works:

Learn much more about Linux in our online course. You can register here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it?

Share