Linux tr Command: Replace, Delete, and Transform Characters in Text
The tr command in Linux swaps one variable for another specified one. This command does not work directly with files, so it must be used with the standard output of another command, with the pipe operator.
The tr command can swap characters from the search variable with the replacement variable, but the number of characters must be the same in both.
The most common options are:
- -d: Deletes occurrences of the search variable;
- -s: Suppresses repeated occurrences of the search variable;
See the example with the grocery list, where tr is used to change all lowercase letters to uppercase:
$ cat lista
arroz
carne
alface
tomate
$ tr [a-z] [A-Z] < listaARROZCARNEALFACETOMATE
The tr command can be useful for converting spaces to TABS in a file:
$ cat arquivo | tr ':[space]:' '\t' > out.txt
It can also fix text by removing spaces:
$ cat domains www. certificacaolinux .com.brwww. kernel .orgwww. nic .br
$ cat domains | tr -d ' 'www.certificacaolinux.com.brwww.kernel.orgwww.nic.br
It can also remove repeated characters:
$ cat domains www.certificacaolinux.......com.brwww.kernel.orgwww.nic.br
$ cat domains | tr -s '.'www.certificacaolinux.com.brwww.kernel.orgwww.nic.br
It can also be used to swap Return "\n" for comma:
$ cat domains | tr -s '.' | tr '\n' ','www.certificacaolinux.com.br,www.kernel.org,www.nic.br,
It can also do the reverse, converting a file with comma-separated items into lines:
$ cat arquivo
Leia Organa,General,Resistência
Luke Skywalker,Jedi,Resistência
$ cat arquivo | tr ',' '\n'
Leia Organa
General
Resistência
Luke Skywalker
Jedi
Resistência
Watch a video of how this command works:
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Liked it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.