fbpx Linux tr Command: Replace & Delete Characters in Text | Certificação Linux

Linux tr Command: Replace, Delete, and Transform Characters in Text

📅 01/01/2019 ⏱ 2 min ✍️ Uira Ribeiro
Linuxcommands
Linux tr Command: Replace, Delete, and Transform Characters in Text
Exam Pass App — mais de 7.000 questões LPI, offline, em 5 idiomas, disponível no Android e na App Store
Available on
Google Play
Available on
App Store

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

Uira Ribeiro

Prof. Uirá Ribeiro

Chair do Board do Linux Professional Institute

After years of watching professionals waste hours on simple tasks because they didn't know the right Linux tools, I decided to teach.
Today I'm the author of most of LPI's official Learning Materials and mentor to over 14,000 certified students.

See my full story →

That was just one piece. The course teaches the whole path — from your first command to exam day.

Certificação Linux — a plataforma líder em certificações Linux no Brasil
WhatsApp