The tr command in Linux: translate and delete characters

Introduction

The commandtr(translate) is an essential tool in the Linux command line that allows you to translate, delete and compress characters from a text input. Although its syntax is simple, its power lies in the ability to process data flows without the need to write complex scripts.

Basic syntax

The general form oftris:

tr [OPCIONES] SET1 [SET2]

WhereSET1defines the set of characters to look for andSET2(optional) the replacement set. If omittedSET2, trremoves the characters ofSET1.

Character translation

One of the most common applications is to change capital letters to lower cases or vice versa.

echo 'hola Mundo' | tr 'a-z' 'A-Z'

This command converts the whole text to capital letters, gettingHOLA MUNDO. Similarly, to move to small cases:

echo 'HOLA Mundo' | tr 'A-Z' 'a-z'

Character removal

If only providedSET1, trDelete those characters from the input.

echo 'hola2023!' | tr -d '0-9'

The result will behola!. Several types of characters can be removed by combining ranges:

echo 'hola, mundo; 2023.' | tr -d ' ,;'

This eliminates spaces, comas and point and coma, leavingholamundo2023.

Compression of repeated characters

With the option-s(squeeze) repeated sequences of the same character can be reduced to a single appearance.

echo 'aaabbbccc' | tr -s 'ab'

The result isabc, since the sequences ofaandbare compressed.

Cases of practical use

  • Clean log files by removing line numbers:cat log.txt | tr -d '0-9'
  • Convert line jumps from Windows (\r\n) to Unix format:tr -d '\r' < archivo.txt
  • Generate random passwords by taking only capital letters and numbers:cat /dev/urandom | tr -dc 'A-Z0-9' | head -c12
  • Remove comments from a shell script (assuming they start with #):tr -d '#' < script.shConsejos y trucosUse --help para ver todas las opciones disponibles.Recuerde que los conjuntos pueden incluir clases de caracteres como [:alpha:], [:digit:] o [:space:].Combine tr con tuberías (|) y otros comandos como sed, awk o grep para flujos de trabajo más sofisticados.Si necesita distinguir entre mayúsculas y minúsculas en la eliminación, especifique ambos rangos explícitamente.ConclusiónEl comando tr es una herramienta ligera pero poderosa que pertenece al repertorio de cualquier administrador de sistemas o desarrollador que trabaje en Linux. Dominar su uso le permitirá realizar transformaciones de texto rápidas y eficientes sin recurrir a lenguajes de programación más pesados.Navegación de entradasPrevious post: El comando sort en Linux: cómo ordenar líneas de texto de forma eficaz Continue ReadingNext post: El comando sed en Linux: editor de flujo para transformar texto Continue ReadingSidebarEspañolInicioEl gran libro de GNU/LinuxEl gran libro de Arch LinuxEl gran libro de UbuntuEl gran libro de SlackwareEl gran libro de Red Hat LinuxEl gran libro de GentooComandos de LinuxProgramas LinuxDistribuciones LinuxSobre el autor:Buscar:CategoríasCategoríasElegir la categoríaComandos de terminal Linux (196)Distribuciones Linux (190)Programas Linux (315)(function() {var dropdown = document.getElementById( "cat" );function onCatChange() {if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) {dropdown.parentNode.submit();}}dropdown.onchange = onCatChange;})();

This work is under aCreative Commons License Attribution 4.0 International for Francesc Roig francesc @ vivaldi.net.

EnglishenEnglishEnglish