Zum Inhalt springen

Tr: Unterschied zwischen den Versionen

Aus Foxwiki
KKeine Bearbeitungszusammenfassung
KKeine Bearbeitungszusammenfassung
Zeile 1: Zeile 1:
Version 76, 2019-05-30
Version 76, 2019-05-30


= {{anchor|RefHeadingToc97913328913898}} Linux- tr =
= Linux- tr =


== {{anchor|RefHeading339881143486078}} Linux- tr ==
== Linux- tr ==


Der Befehl tr (von '''tr'''anslate = umwandeln oder '''tr'''ansliterate = transliterieren) dient dazu, in Texten systematisch Zeichen durch andere Zeichen zu ersetzen. So ist es beispielweise möglich, alle Großbuchstaben einer Datei durch Kleinbuchstaben zu ersetzen oder mehrere aufeinander folgende Leerzeichen durch ein einziges zu ersetzen. Für komplexere Ersetzungen, z.B. für ganze Wörter, empfiehlt sich das wesentlich mächtigere [https://wiki.ubuntuusers.de/sed/ sed].  
Der Befehl tr (von '''tr'''anslate = umwandeln oder '''tr'''ansliterate = transliterieren) dient dazu, in Texten systematisch Zeichen durch andere Zeichen zu ersetzen. So ist es beispielweise möglich, alle Großbuchstaben einer Datei durch Kleinbuchstaben zu ersetzen oder mehrere aufeinander folgende Leerzeichen durch ein einziges zu ersetzen. Für komplexere Ersetzungen, z.B. für ganze Wörter, empfiehlt sich das wesentlich mächtigere [https://wiki.ubuntuusers.de/sed/ sed].  


=== {{anchor|RefHeadingToc6371523260012}} Aufruf ===
=== Aufruf ===


Die allgemeine Syntax lautet [https://wiki.ubuntuusers.de/tr/#source-1 [1]]:
Die allgemeine Syntax lautet [https://wiki.ubuntuusers.de/tr/#source-1 [1]]:


<div style="margin-left:0cm;margin-right:0cm;">tr OPTION ZEICHENFOLGE1 ZEICHENFOLGE2 </div>
tr OPTION ZEICHENFOLGE1 ZEICHENFOLGE2  


<tt>tr</tt> kennt folgende Optionen:
<tt>tr</tt> kennt folgende Optionen:




{| style="border-spacing:0;margin:auto;width:17.501cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
| colspan="2" | Optionen von <tt>tr</tt>  
| colspan="2" | Optionen von <tt>tr</tt>  
|- style="border:none;padding:0.049cm;"
|-  
|| Option  
|| Option  
|| Beschreibung  
|| Beschreibung  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>-c</tt>, <tt>-C</tt> oder <tt>--complement</tt>  
|| <tt>-c</tt>, <tt>-C</tt> oder <tt>--complement</tt>  
|| Komplement der angegebenen Zeichenfolge  
|| Komplement der angegebenen Zeichenfolge  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>-d</tt> oder <tt>--delete</tt>  
|| <tt>-d</tt> oder <tt>--delete</tt>  
|| Löschen (nicht Ersetzen) von Zeichen  
|| Löschen (nicht Ersetzen) von Zeichen  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>-s</tt> oder <tt>--squeeze-repeats</tt>  
|| <tt>-s</tt> oder <tt>--squeeze-repeats</tt>  
|| Mehrere identische aufeinanderfolgende Zeichen durch ein einzelnes ersetzen  
|| Mehrere identische aufeinanderfolgende Zeichen durch ein einzelnes ersetzen  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>-t</tt> oder <tt>--truncate-set1</tt>  
|| <tt>-t</tt> oder <tt>--truncate-set1</tt>  
|| Beschneide zunächst den ersten Datensatz auf die Länge des zweiten Datensatzes  
|| Beschneide zunächst den ersten Datensatz auf die Länge des zweiten Datensatzes  
Zeile 41: Zeile 41:




{| style="border-spacing:0;margin:auto;width:17.501cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
| colspan="2" | Von <tt>tr</tt> interpretierte Befehlssequenzen  
| colspan="2" | Von <tt>tr</tt> interpretierte Befehlssequenzen  
|- style="border:none;padding:0.049cm;"
|-  
|| Option  
|| Option  
|| Beschreibung  
|| Beschreibung  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>\\</tt>  
|| <tt>\\</tt>  
|| Backslash  
|| Backslash  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>\b</tt>  
|| <tt>\b</tt>  
|| Rücktaste  
|| Rücktaste  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>\n</tt>  
|| <tt>\n</tt>  
|| Zeilenumbruch  
|| Zeilenumbruch  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>\t</tt>  
|| <tt>\t</tt>  
|| Horizontaler Tab  
|| Horizontaler Tab  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>ZEICHEN1-ZEICHEN 2</tt>  
|| <tt>ZEICHEN1-ZEICHEN 2</tt>  
|| Alle Zeichen von ZEICHEN 1 bis ZEICHEN2  
|| Alle Zeichen von ZEICHEN 1 bis ZEICHEN2  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>[:alpha:]</tt>  
|| <tt>[:alpha:]</tt>  
|| Alle Buchstaben  
|| Alle Buchstaben  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>[:blank:]</tt>  
|| <tt>[:blank:]</tt>  
|| Alle horizontalen Leerzeichen  
|| Alle horizontalen Leerzeichen  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>[:digit:]</tt>  
|| <tt>[:digit:]</tt>  
|| Alle Zahlen  
|| Alle Zahlen  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>[:lower:]</tt>  
|| <tt>[:lower:]</tt>  
|| Alle Kleinbuchstuben  
|| Alle Kleinbuchstuben  
|- style="border:none;padding:0.049cm;"
|-  
|| <tt>[:upper:]</tt>  
|| <tt>[:upper:]</tt>  
|| Alle Großbuchstaben  
|| Alle Großbuchstaben  
Zeile 81: Zeile 81:
Weitere Angaben sind der [https://wiki.ubuntuusers.de/man/ Manpage] zu entnehmen. Man beachte, dass die [https://wiki.ubuntuusers.de/Zsh/ Zsh] die eckigen Klammern z.B. in <tt>[:blank:]</tt> als Wildcard-Parameter interpretiert und sie daher nicht an <tt>tr</tt> weitergibt. Benutzer der Zsh sollten solche Argument daher in einfache oder doppelte Anführungszeichen einschließen.
Weitere Angaben sind der [https://wiki.ubuntuusers.de/man/ Manpage] zu entnehmen. Man beachte, dass die [https://wiki.ubuntuusers.de/Zsh/ Zsh] die eckigen Klammern z.B. in <tt>[:blank:]</tt> als Wildcard-Parameter interpretiert und sie daher nicht an <tt>tr</tt> weitergibt. Benutzer der Zsh sollten solche Argument daher in einfache oder doppelte Anführungszeichen einschließen.


=== {{anchor|RefHeadingToc6391523260012}} Beispiele ===
=== Beispiele ===


Ein einfaches Beispiel ist das Ersetzen eines Buchstabens durch einen anderen:
Ein einfaches Beispiel ist das Ersetzen eines Buchstabens durch einen anderen:


<div style="margin-left:0cm;margin-right:0cm;">echo Maus | tr M H  
echo Maus | tr M H  
  Haus</div>
  Haus


Mit folgendem Befehl werden Groß- in Kleinbuchstaben umgewandelt:  
Mit folgendem Befehl werden Groß- in Kleinbuchstaben umgewandelt:  


<div style="margin-left:0cm;margin-right:0cm;">echo 'FLÜSTERN' | tr A-ZÄÖÜ a-zäöü </div>
echo 'FLÜSTERN' | tr A-ZÄÖÜ a-zäöü  


oder auch  
oder auch  


<div style="margin-left:0cm;margin-right:0cm;">echo 'FLÜSTERN' | tr [:upper:]ÄÖÜ [:lower:]äöü </div>
echo 'FLÜSTERN' | tr [:upper:]ÄÖÜ [:lower:]äöü  


ergibt  
ergibt  


<div style="margin-left:0cm;margin-right:0cm;">flüstern</div>
flüstern


… und umgekehrt:
… und umgekehrt:


<div style="margin-left:0cm;margin-right:0cm;">echo 'schreien' | tr a-zäöü A-ZÄÖÜ  
echo 'schreien' | tr a-zäöü A-ZÄÖÜ  
  SCHREIEN</div>
  SCHREIEN


Bestimmte Zeichen, hier alle Zahlen in der Datei '''datei.txt''', lassen sich mit der Option <tt>-d</tt> löschen:  
Bestimmte Zeichen, hier alle Zahlen in der Datei '''datei.txt''', lassen sich mit der Option <tt>-d</tt> löschen:  


<div style="margin-left:0cm;margin-right:0cm;">tr -d '0-9' < datei.txt </div>
tr -d '0-9' < datei.txt  


Soll aus mehrere aufeinanderfolgenden Leerzeichen ein einzelnes gemacht werden, kann man die Option <tt>-s</tt> verwenden:  
Soll aus mehrere aufeinanderfolgenden Leerzeichen ein einzelnes gemacht werden, kann man die Option <tt>-s</tt> verwenden:  


<div style="margin-left:0cm;margin-right:0cm;">echo 'd    b' |tr -s ' '  
echo 'd    b' |tr -s ' '  
  d b</div>
  d b


Um alle Zeichen zu entfernen, die '''nicht''' einer bestimmten Zeichengruppe angehören, kann die Option <tt>-c</tt> benutzt werden. Im folgenden Beispiel werden alle Zeichen entfernt, die keine Buchstaben sind:
Um alle Zeichen zu entfernen, die '''nicht''' einer bestimmten Zeichengruppe angehören, kann die Option <tt>-c</tt> benutzt werden. Im folgenden Beispiel werden alle Zeichen entfernt, die keine Buchstaben sind:


<div style="margin-left:0cm;margin-right:0cm;">echo 'Die drei ??? treffen die 12 Geschworenen!' | tr -cd '[:alpha:]' > datei  
echo 'Die drei ??? treffen die 12 Geschworenen!' | tr -cd '[:alpha:]' > datei  
  cat datei  
  cat datei  
  DiedreitreffendieGeschworenen</div>
  DiedreitreffendieGeschworenen


Mit Hilfe von tr lässt sich ein Text auch sehr leicht [https://de.wikipedia.org/wiki/Rot13 Rot13] chiffrieren und dechiffieren:
Mit Hilfe von tr lässt sich ein Text auch sehr leicht [https://de.wikipedia.org/wiki/Rot13 Rot13] chiffrieren und dechiffieren:


<div style="margin-left:0cm;margin-right:0cm;">echo 'Morgen bringen wir Cäsar um' | tr [a-zA-Z] [n-za-mN-ZA-M]  
echo 'Morgen bringen wir Cäsar um' | tr [a-zA-Z] [n-za-mN-ZA-M]  
  Zbetra oevatra jve Päfne hz</div>
  Zbetra oevatra jve Päfne hz


Und wieder zurück:
Und wieder zurück:


<div style="margin-left:0cm;margin-right:0cm;">echo 'Zbetra oevatra jve Päfne hz' | tr [a-zA-Z] [n-za-mN-ZA-M]  
echo 'Zbetra oevatra jve Päfne hz' | tr [a-zA-Z] [n-za-mN-ZA-M]  
  Morgen bringen wir Cäsar um</div>
  Morgen bringen wir Cäsar um


Um in einer Datei Zeichen zu ändern und das Ergebnis in eine zweite Datei zu schreiben, können [https://wiki.ubuntuusers.de/Shell/Umleitungen/ Umleitungen] eingesetzt werden. Mit dem folgenden Befehl werden alle Vorkommen des Buchstabens a in '''datei1''' in den Buchstaben b umgewandelt und das Ergebnis in '''datei2''' geschrieben:  
Um in einer Datei Zeichen zu ändern und das Ergebnis in eine zweite Datei zu schreiben, können [https://wiki.ubuntuusers.de/Shell/Umleitungen/ Umleitungen] eingesetzt werden. Mit dem folgenden Befehl werden alle Vorkommen des Buchstabens a in '''datei1''' in den Buchstaben b umgewandelt und das Ergebnis in '''datei2''' geschrieben:  


<div style="margin-left:0cm;margin-right:0cm;">tr a b < datei1 > datei2 </div>
tr a b < datei1 > datei2  


Der folgende Befehl entfernt alle Wagenrückläufe („Carriage Return“, mehr unter [https://wiki.ubuntuusers.de/Zeichensatz-Konverter/ Zeichensatz-Konverter]) und konvertiert so eine Datei '''datei1''' vom Windows- in das Unixformat:  
Der folgende Befehl entfernt alle Wagenrückläufe („Carriage Return“, mehr unter [https://wiki.ubuntuusers.de/Zeichensatz-Konverter/ Zeichensatz-Konverter]) und konvertiert so eine Datei '''datei1''' vom Windows- in das Unixformat:  


<div style="margin-left:0cm;margin-right:0cm;">tr -d '\r' < datei1 > ausgabedatei </div>
tr -d '\r' < datei1 > ausgabedatei  


Alle mehrfach aufeinander folgenden Zeilenumbrüche („new line“) in '''datei1''' werden in jeweils einen umgewandelt:  
Alle mehrfach aufeinander folgenden Zeilenumbrüche („new line“) in '''datei1''' werden in jeweils einen umgewandelt:  


<div style="margin-left:0cm;margin-right:0cm;">tr -s '\n' < datei1 > ausgabedatei </div>
tr -s '\n' < datei1 > ausgabedatei  


Der folgende Befehl führt dazu, dass alle kommaseparierten Elemente einer [https://de.wikipedia.org/wiki/CSV_(Dateiformat) CSV]-Datei '''datei.csv''' jeweils in einer neuen Zeile erscheinen:  
Der folgende Befehl führt dazu, dass alle kommaseparierten Elemente einer [https://de.wikipedia.org/wiki/CSV_(Dateiformat) CSV]-Datei '''datei.csv''' jeweils in einer neuen Zeile erscheinen:  


<div style="margin-left:0cm;margin-right:0cm;">tr ',' '\n' < datei.csv </div>
tr ',' '\n' < datei.csv  


== {{anchor|RefHeadingToc6431523260012}} tr ==
== tr ==


'''tr''' ist ein [https://de.wikipedia.org/wiki/Unix-Kommando Unix-Kommando], dessen Name eine Abkürzung für ''translate'' (''deutsch:'' übersetzen) ist, das bestimmte Zeichen aus einem Datenstrom ersetzt oder entfernt.  
'''tr''' ist ein [https://de.wikipedia.org/wiki/Unix-Kommando Unix-Kommando], dessen Name eine Abkürzung für ''translate'' (''deutsch:'' übersetzen) ist, das bestimmte Zeichen aus einem Datenstrom ersetzt oder entfernt.  
Zeile 156: Zeile 156:
Beispiel:  
Beispiel:  


<div style="margin-left:0cm;margin-right:0cm;">$ echo Meyer | tr y i</div>
$ echo Meyer | tr y i
<div style="margin-left:0cm;margin-right:0cm;">Meier</div>
Meier


Es sind mehrfache Ersetzungen einzelner Zeichen auf einmal möglich. Z.B. ersetzt  
Es sind mehrfache Ersetzungen einzelner Zeichen auf einmal möglich. Z.B. ersetzt  


<div style="margin-left:0cm;margin-right:0cm;">tr 'abcd' 'jkmn'</div>
tr 'abcd' 'jkmn'


alle vorkommenden ''a'' durch ''j'', ''b'' durch ''k'' usw.  
alle vorkommenden ''a'' durch ''j'', ''b'' durch ''k'' usw.  
Zeile 167: Zeile 167:
Im Alphabet aufeinanderfolgende Zeichen lassen sich dabei mit einem Bindestrich angeben:  
Im Alphabet aufeinanderfolgende Zeichen lassen sich dabei mit einem Bindestrich angeben:  


<div style="margin-left:0cm;margin-right:0cm;">tr 'a-d' 'jkmn'</div>
tr 'a-d' 'jkmn'


Mit dem Operator ''s'' werden alle hintereinander folgenden identischen Zeichen durch ein einzelnes ersetzt. Beispiel:  
Mit dem Operator ''s'' werden alle hintereinander folgenden identischen Zeichen durch ein einzelnes ersetzt. Beispiel:  


echo muuuuh | tr -s u
echo muuuuh | tr -s u
<div style="margin-left:0cm;margin-right:0cm;">muh</div>
muh


Der Operand ''d'' löscht alle im ersten Argument angegebenen Zeichen  
Der Operand ''d'' löscht alle im ersten Argument angegebenen Zeichen  


<div style="margin-left:0cm;margin-right:0cm;">tr -d '\r'</div>
tr -d '\r'


wobei \r für ein Carriage Return (Bytewert 13) steht. Mit diesem Befehl wird dieses unter Unix nicht verwendete Umbruchzeichen ersatzlos entfernt.  
wobei \r für ein Carriage Return (Bytewert 13) steht. Mit diesem Befehl wird dieses unter Unix nicht verwendete Umbruchzeichen ersatzlos entfernt.  
Zeile 182: Zeile 182:
Ist ein ''c'' angegeben, so gilt die Umkehrung, also hier  
Ist ein ''c'' angegeben, so gilt die Umkehrung, also hier  


<div style="margin-left:0cm;margin-right:0cm;">tr -cd '[:alnum:]' </div>
tr -cd '[:alnum:]'  


wobei der Ausdruck [:alnum:] für alle alphanumerischen Zeichen steht. Somit werden alle nicht alphanumerischen Zeichen entfernt.  
wobei der Ausdruck [:alnum:] für alle alphanumerischen Zeichen steht. Somit werden alle nicht alphanumerischen Zeichen entfernt.  


== {{anchor|RefHeadingToc6491523260012}} tr für Anfänger ==
== tr für Anfänger ==


Abhängig von der Art der Arbeit, die Sie auf der Kommandozeile unter Linux erledigen, können Sie ein Dienstprogramm wünschen, das als Schweizer Taschenmesser für die schnelle Textbearbeitung fungieren kann. Gerne gibt es ein Tool namens tr, das sich für diese Rolle qualifiziert. In diesem Tutorial werden wir die Grundlagen von tr anhand einiger leicht verständlicher Beispiele diskutieren.
Abhängig von der Art der Arbeit, die Sie auf der Kommandozeile unter Linux erledigen, können Sie ein Dienstprogramm wünschen, das als Schweizer Taschenmesser für die schnelle Textbearbeitung fungieren kann. Gerne gibt es ein Tool namens tr, das sich für diese Rolle qualifiziert. In diesem Tutorial werden wir die Grundlagen von tr anhand einiger leicht verständlicher Beispiele diskutieren.
Zeile 194: Zeile 194:
So erklärt es die Man Page des Tools:
So erklärt es die Man Page des Tools:


<div style="margin-left:0cm;margin-right:0cm;">Translate, squeeze, and/or delete characters from standard input, writing to standard output.</div>
Translate, squeeze, and/or delete characters from standard input, writing to standard output.


Und folgendes ist seine Syntax:
Und folgendes ist seine Syntax:


<div style="margin-left:0cm;margin-right:0cm;">tr [OPTION]... SET1 [SET2]</div>
tr [OPTION]... SET1 [SET2]


hier ist, was SET bedeutet:
hier ist, was SET bedeutet:


<div style="margin-left:0cm;margin-right:0cm;">SETs are specified as strings of characters.&nbsp; Most represent themselves.&nbsp; Interpreted sequences are:</div>
SETs are specified as strings of characters.&nbsp; Most represent themselves.&nbsp; Interpreted sequences are:
<div style="margin-left:0cm;margin-right:0cm;">\NNN&nbsp;&nbsp; character with octal value NNN (1 to 3 octal digits)
\NNN&nbsp;&nbsp; character with octal value NNN (1 to 3 octal digits)
  \\&nbsp;&nbsp;&nbsp;&nbsp; backslash
  \\&nbsp;&nbsp;&nbsp;&nbsp; backslash
  \a&nbsp;&nbsp;&nbsp;&nbsp; audible BEL
  \a&nbsp;&nbsp;&nbsp;&nbsp; audible BEL
Zeile 211: Zeile 211:
  \r&nbsp;&nbsp;&nbsp;&nbsp; return
  \r&nbsp;&nbsp;&nbsp;&nbsp; return
  \t&nbsp;&nbsp;&nbsp;&nbsp; horizontal tab
  \t&nbsp;&nbsp;&nbsp;&nbsp; horizontal tab
  \v&nbsp;&nbsp;&nbsp;&nbsp; vertical tab</div>
  \v&nbsp;&nbsp;&nbsp;&nbsp; vertical tab


=== {{anchor|RefHeadingToc6531523260012}} Klein- in Großbuchstaben ===
=== Klein- in Großbuchstaben ===


Angenommen, du möchtest den Satz „linux tutorial on howtoforge“ in Großbuchstaben konvertieren, dann ist hier, wie du dies mit tr tun kannst.
Angenommen, du möchtest den Satz „linux tutorial on howtoforge“ in Großbuchstaben konvertieren, dann ist hier, wie du dies mit tr tun kannst.


<div style="margin-left:0cm;margin-right:0cm;">echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"</div>
echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"


Der obige Befehl erzeugte die folgende Ausgabe auf meinem System:
Der obige Befehl erzeugte die folgende Ausgabe auf meinem System:


<div style="margin-left:0cm;margin-right:0cm;">LINUX TUTORIAL ON HOWTOFORGE</div>
LINUX TUTORIAL ON HOWTOFORGE


=== {{anchor|RefHeadingToc6551523260012}} Zusätzliche Räume abstreifen ===
=== Zusätzliche Räume abstreifen ===


Angenommen, Sie haben eine Zeile wie: „HowtoForge ist eine extrem gute Ressource für Linux-Tutorials“. Und die Anforderung ist, zusätzliche Räume von dieser Linie zu entfernen.
Angenommen, Sie haben eine Zeile wie: „HowtoForge ist eine extrem gute Ressource für Linux-Tutorials“. Und die Anforderung ist, zusätzliche Räume von dieser Linie zu entfernen.
Zeile 229: Zeile 229:
Hier ist, wie du tr verwenden kannst, um dies zu tun:
Hier ist, wie du tr verwenden kannst, um dies zu tun:


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; good resource for&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux tutorials' | tr -s '[:space:]'</div>
echo 'HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; good resource for&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux tutorials' | tr -s '[:space:]'


Hier ist die Ausgabe:
Hier ist die Ausgabe:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge is an extremely good resource for Linux tutorials</div>
HowtoForge is an extremely good resource for Linux tutorials


=== {{anchor|RefHeadingToc6571523260012}} Text löschen ===
=== Text löschen ===


Angenommen, Sie möchten die Bindestriche aus der folgenden Zeile löschen: „HowtoForge — ist — ein — extrem — gut — Ressource — für — Linux — Tutorials.“ Dann ist hier, wie Sie dies mit tr tun können.
Angenommen, Sie möchten die Bindestriche aus der folgenden Zeile löschen: „HowtoForge — ist — ein — extrem — gut — Ressource — für — Linux — Tutorials.“ Dann ist hier, wie Sie dies mit tr tun können.


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'</div>
echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'


Es folgt der Output, den es produziert:
Es folgt der Output, den es produziert:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge&nbsp; is&nbsp; an&nbsp; extremely&nbsp; good&nbsp; resource&nbsp; for&nbsp; Linux&nbsp; tutorials</div>
HowtoForge&nbsp; is&nbsp; an&nbsp; extremely&nbsp; good&nbsp; resource&nbsp; for&nbsp; Linux&nbsp; tutorials


=== {{anchor|RefHeadingToc6591523260012}} Zeichen ersetzen ===
=== Zeichen ersetzen ===


Im vorherigen Abschnitt nehmen wir an, dass die Anforderung darin bestand, Bindestriche durch, sagen wir, Punkte zu ersetzen. Dann ist hier, wie du das mit tr machen kannst.
Im vorherigen Abschnitt nehmen wir an, dass die Anforderung darin bestand, Bindestriche durch, sagen wir, Punkte zu ersetzen. Dann ist hier, wie du das mit tr machen kannst.


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'</div>
echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'


Es folgt der Output, den es produziert hat:
Es folgt der Output, den es produziert hat:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials</div>
HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials


== {{anchor|RefHeadingToc6631523260012}} tr ==
== tr ==


'''tr''' is a very useful UNIX command. It is used to transform string or delete characters from the string. Various type of transformation can be done by using this command, such as searching and replacing text, transforming string from uppercase to lowercase or vice versa, removing repeated characters from the string etc. The command can be used for some complicated transformation also. The different uses of '''tr '''command are shown in this tutorial.
'''tr''' is a very useful UNIX command. It is used to transform string or delete characters from the string. Various type of transformation can be done by using this command, such as searching and replacing text, transforming string from uppercase to lowercase or vice versa, removing repeated characters from the string etc. The command can be used for some complicated transformation also. The different uses of '''tr '''command are shown in this tutorial.
Zeile 261: Zeile 261:
'''Syntax:'''
'''Syntax:'''


<div style="margin-left:0cm;margin-right:0cm;">'''tr [option] stringValue1 [stringValue2]'''</div>
'''tr [option] stringValue1 [stringValue2]'''


'''option''' and '''stringValue2''' are optional for '''tr''' command. You can use '''-c, -s''' and '''-d''' option with '''tr '''command to do different types of tasks.
'''option''' and '''stringValue2''' are optional for '''tr''' command. You can use '''-c, -s''' and '''-d''' option with '''tr '''command to do different types of tasks.


=== {{anchor|RefHeadingToc6651523260012}} Change case ===
=== Change case ===


You can change the case of the string very easily by using tr command. To define uppercase, you can use [:upper:] or [A-Z] and to define lowercase you can define [:lower:] or [a-z].
You can change the case of the string very easily by using tr command. To define uppercase, you can use [:upper:] or [A-Z] and to define lowercase you can define [:lower:] or [a-z].
Zeile 271: Zeile 271:
tr command can be used in the following way to convert any string from uppercase to lowercase.
tr command can be used in the following way to convert any string from uppercase to lowercase.


<div style="margin-left:0cm;margin-right:0cm;">'''tr [:upper:] [:lower:]'''</div>
'''tr [:upper:] [:lower:]'''


You can use tr command in the following way also to convert any string from lowercase to uppercase.
You can use tr command in the following way also to convert any string from lowercase to uppercase.


<div style="margin-left:0cm;margin-right:0cm;">'''tr a-z A-Z'''</div>
'''tr a-z A-Z'''


Run the following command to convert every small letter of the string,’'''linuxhint'''’ into the capital letter.
Run the following command to convert every small letter of the string,’'''linuxhint'''’ into the capital letter.


<div style="margin-left:0cm;margin-right:0cm;">$ echo linuxhint | tr [:lower:] [:upper:]</div>
$ echo linuxhint | tr [:lower:] [:upper:]


You can apply tr command for converting the content of any text file from upper to lower or lower to upper. Suppose, you have text file named, '''items.txt '''with the following contents.# Monitor  
You can apply tr command for converting the content of any text file from upper to lower or lower to upper. Suppose, you have text file named, '''items.txt '''with the following contents.# Monitor  
Zeile 291: Zeile 291:
Run the following commands from the terminal to display the content of items.txt and the output of tr command after converting the content of that file from lower to upper case. The following tr command will not modify the original content of the file.
Run the following commands from the terminal to display the content of items.txt and the output of tr command after converting the content of that file from lower to upper case. The following tr command will not modify the original content of the file.


<div style="margin-left:0cm;margin-right:0cm;">$ cat items.txt
$ cat items.txt
  $ tr a-z A-Z < items.txt</div>
  $ tr a-z A-Z < items.txt


You can run the following command to store the output of the '''tr''' command into another file named ‘'''output.txt'''’.
You can run the following command to store the output of the '''tr''' command into another file named ‘'''output.txt'''’.


<div style="margin-left:0cm;margin-right:0cm;">$ tr [:upper:] [:lower:] < items.txt > output.txt
$ tr [:upper:] [:lower:] < items.txt > output.txt
  $ cat output.txt</div>
  $ cat output.txt


=== {{anchor|RefHeadingToc6671523260012}} Translate character  ===
=== Translate character  ===


tr command can be used to search and replace any particular character from any text. The following command is used to convert each space of the text, “'''Welcome to Linuxhint'''” by newline (\n).
tr command can be used to search and replace any particular character from any text. The following command is used to convert each space of the text, “'''Welcome to Linuxhint'''” by newline (\n).


<div style="margin-left:0cm;margin-right:0cm;">$ echo "Welcome To Linuxhint" | tr [:space:] '\n'</div>
$ echo "Welcome To Linuxhint" | tr [:space:] '\n'


=== {{anchor|RefHeadingToc6691523260012}} –c option ===
=== –c option ===


tr command can be used with -c option to replace those characters with the second character that don’t match with the first character value. In the following example, tr command is used to search those characters in the string ‘'''bash'''’ that don’t match with the character ‘'''b'''’ and replace them by ‘'''a'''’. The output is ‘'''baaaa'''’. Four characters are converted here. These are ,’a’,’s’,’h’ and ‘\n’.
tr command can be used with -c option to replace those characters with the second character that don’t match with the first character value. In the following example, tr command is used to search those characters in the string ‘'''bash'''’ that don’t match with the character ‘'''b'''’ and replace them by ‘'''a'''’. The output is ‘'''baaaa'''’. Four characters are converted here. These are ,’a’,’s’,’h’ and ‘\n’.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "bash" | tr -c 'b' 'a'</div>
$ echo "bash" | tr -c 'b' 'a'


=== {{anchor|RefHeadingToc6711523260012}} –s option ===
=== –s option ===


tr command uses '''–s '''option for search and replace any string from a text. In the following example, space (‘ ‘) is replaced by tab (‘\t’).
tr command uses '''–s '''option for search and replace any string from a text. In the following example, space (‘ ‘) is replaced by tab (‘\t’).


<div style="margin-left:0cm;margin-right:0cm;">$ echo "BASH Programming" | tr -s ' ' '\t'</div>
$ echo "BASH Programming" | tr -s ' ' '\t'


You can use both -c and -s options together with tr command. In the following example, the range of small letter is used as the first string value. For –c option, tr command will search and replace each capital letter by newline (‘\n’) of the file, '''items.txt''' and store the output of the command in the file, '''output.txt'''.
You can use both -c and -s options together with tr command. In the following example, the range of small letter is used as the first string value. For –c option, tr command will search and replace each capital letter by newline (‘\n’) of the file, '''items.txt''' and store the output of the command in the file, '''output.txt'''.


<div style="margin-left:0cm;margin-right:0cm;">$ cat items.txt
$ cat items.txt
  $ tr -cs [a-z] "\n" < items.txt > output.txt
  $ tr -cs [a-z] "\n" < items.txt > output.txt
  $ cat output.txt</div>
  $ cat output.txt


=== {{anchor|RefHeadingToc6731523260012}} –d option  ===
=== –d option  ===


'''-d''' option used with tr command to search and delete any character or string from a text.&nbsp; In the following example, tr command will search ‘'''P'''’, ‘'''y’''' and ‘'''t'''’ in the string “'''Python is a Programming language”''' and delete those characters.
'''-d''' option used with tr command to search and delete any character or string from a text.&nbsp; In the following example, tr command will search ‘'''P'''’, ‘'''y’''' and ‘'''t'''’ in the string “'''Python is a Programming language”''' and delete those characters.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "Python is a Programming language" | tr -d 'Pyt'</div>
$ echo "Python is a Programming language" | tr -d 'Pyt'


'''-c''' option can be used with '''–d''' option in the tr command to complement the search like precious –cs command. In the following example, tr command with '''–cd''' will search all non-digit characters from the string, “'''Phone No: 985634854'''” and delete them.
'''-c''' option can be used with '''–d''' option in the tr command to complement the search like precious –cs command. In the following example, tr command with '''–cd''' will search all non-digit characters from the string, “'''Phone No: 985634854'''” and delete them.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "Phone No: 985634854" | tr -cd '0-9'</div>
$ echo "Phone No: 985634854" | tr -cd '0-9'


In a similar way, you can run use '''-cd''' option in '''tr''' command like the following command to remove the non-printable characters from a file. No nonprintable character exists in '''items.txt'''. So the output will be the same as the file content.
In a similar way, you can run use '''-cd''' option in '''tr''' command like the following command to remove the non-printable characters from a file. No nonprintable character exists in '''items.txt'''. So the output will be the same as the file content.


<div style="margin-left:0cm;margin-right:0cm;">$ tr -cd "[:print:]" < items.txt</div>
$ tr -cd "[:print:]" < items.txt


=== {{anchor|RefHeadingToc15501523260012}} Conclusion ===
=== Conclusion ===


The basic uses of '''tr '''command are explained here by using various examples. Hope, this tutorial will help you to learn the purposes of using this command.  
The basic uses of '''tr '''command are explained here by using various examples. Hope, this tutorial will help you to learn the purposes of using this command.  


=== {{anchor|RefHeadingToc6751523260012}} Linux tr command ===
=== Linux tr command ===


Depending on the kind of work you do on the command line in Linux, you may want a utility that can act as a Swiss army knife of quick text editing. Gladly, there exists a tool dubbed tr, which qualifies for this role. In this tutorial, we will discuss the basics of tr using some easy to understand examples.
Depending on the kind of work you do on the command line in Linux, you may want a utility that can act as a Swiss army knife of quick text editing. Gladly, there exists a tool dubbed tr, which qualifies for this role. In this tutorial, we will discuss the basics of tr using some easy to understand examples.
Zeile 347: Zeile 347:
Here's how the tool's man page explains it:
Here's how the tool's man page explains it:


<div style="margin-left:0cm;margin-right:0cm;">Translate, squeeze, and/or delete characters from standard input, writing to standard output.</div>
Translate, squeeze, and/or delete characters from standard input, writing to standard output.


And following is its syntax:
And following is its syntax:


<div style="margin-left:0cm;margin-right:0cm;">tr [OPTION]... SET1 [SET2]</div>
tr [OPTION]... SET1 [SET2]


here's what SET means:
here's what SET means:
Zeile 357: Zeile 357:
<tt>SETs are specified as strings of characters.&nbsp; Most represent themselves.&nbsp; Interpreted sequences are:</tt>
<tt>SETs are specified as strings of characters.&nbsp; Most represent themselves.&nbsp; Interpreted sequences are:</tt>


<div style="margin-left:0cm;margin-right:0cm;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \NNN&nbsp;&nbsp; character with octal value NNN (1 to 3 octal digits)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \NNN&nbsp;&nbsp; character with octal value NNN (1 to 3 octal digits)
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \\&nbsp;&nbsp;&nbsp;&nbsp; backslash
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \\&nbsp;&nbsp;&nbsp;&nbsp; backslash
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \a&nbsp;&nbsp;&nbsp;&nbsp; audible BEL
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \a&nbsp;&nbsp;&nbsp;&nbsp; audible BEL
Zeile 365: Zeile 365:
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \r&nbsp;&nbsp;&nbsp;&nbsp; return
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \r&nbsp;&nbsp;&nbsp;&nbsp; return
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \t&nbsp;&nbsp;&nbsp;&nbsp; horizontal tab
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \t&nbsp;&nbsp;&nbsp;&nbsp; horizontal tab
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \v&nbsp;&nbsp;&nbsp;&nbsp; vertical tab</div>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \v&nbsp;&nbsp;&nbsp;&nbsp; vertical tab


=== {{anchor|RefHeadingToc6811523260012}} lower case to upper case ===
=== lower case to upper case ===


Suppose you want to convert the sentence "linux tutorial on howtoforge" to uppercase, then here's how you can do this using tr.
Suppose you want to convert the sentence "linux tutorial on howtoforge" to uppercase, then here's how you can do this using tr.


<div style="margin-left:0cm;margin-right:0cm;">echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"</div>
echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"


The above command produced the following output on my system:
The above command produced the following output on my system:


<div style="margin-left:0cm;margin-right:0cm;">LINUX TUTORIAL ON HOWTOFORGE</div>
LINUX TUTORIAL ON HOWTOFORGE


=== {{anchor|RefHeadingToc6831523260012}} Strip extra spaces ===
=== Strip extra spaces ===


Suppose you have a line like: "HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely &nbsp; &nbsp; &nbsp;&nbsp; good resource for &nbsp; &nbsp;&nbsp; Linux tutorials". And the requirement is to strip extra spaces from this line.
Suppose you have a line like: "HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely &nbsp; &nbsp; &nbsp;&nbsp; good resource for &nbsp; &nbsp;&nbsp; Linux tutorials". And the requirement is to strip extra spaces from this line.
Zeile 383: Zeile 383:
Here's how you can use tr to do this:
Here's how you can use tr to do this:


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; good resource for&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux tutorials' | tr -s '[:space:]'</div>
echo 'HowtoForge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is an extremely&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; good resource for&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Linux tutorials' | tr -s '[:space:]'


Here's the output:
Here's the output:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge is an extremely good resource for Linux tutorials</div>
HowtoForge is an extremely good resource for Linux tutorials


=== {{anchor|RefHeadingToc6851523260012}} Delete text ===
=== Delete text ===


Suppose you want to delete the hyphens from the following line: "HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials." Then here's how you can do this using tr.
Suppose you want to delete the hyphens from the following line: "HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials." Then here's how you can do this using tr.


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'</div>
echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'


Following is the output it produces:
Following is the output it produces:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge&nbsp; is&nbsp; an&nbsp; extremely&nbsp; good&nbsp; resource&nbsp; for&nbsp; Linux&nbsp; tutorials</div>
HowtoForge&nbsp; is&nbsp; an&nbsp; extremely&nbsp; good&nbsp; resource&nbsp; for&nbsp; Linux&nbsp; tutorials


=== {{anchor|RefHeadingToc6871523260012}} Replace characters ===
=== Replace characters ===


In the previous section, suppose the requirement was to replace hyphens with, let's say, dots. Then here's how you can do that using tr.
In the previous section, suppose the requirement was to replace hyphens with, let's say, dots. Then here's how you can do that using tr.


<div style="margin-left:0cm;margin-right:0cm;">echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'</div>
echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'


Following is the output it produced:
Following is the output it produced:


<div style="margin-left:0cm;margin-right:0cm;">HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials</div>
HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials


== {{anchor|RefHeadingToc6911523260012}} tr examples ==
== tr examples ==


Along with [https://www.linuxnix.com/sedsteam-editor-explained-detail-linuxunix/ the Linux sed command], the tr command stands for translate is used to provide a level of swapping or translation, suppression or deletion of files. The tr command just translates one character to another character. In this article, we’ll share a couple of examples demonstrating some exciting things that we can do with the tr command.
Along with [https://www.linuxnix.com/sedsteam-editor-explained-detail-linuxunix/ the Linux sed command], the tr command stands for translate is used to provide a level of swapping or translation, suppression or deletion of files. The tr command just translates one character to another character. In this article, we’ll share a couple of examples demonstrating some exciting things that we can do with the tr command.


=== {{anchor|RefHeadingToc6931523260012}} Basic syntax ===
=== Basic syntax ===


<div style="margin-left:0cm;margin-right:0cm;">'''tr [OPTION] [SET1] [SET2]'''</div>
'''tr [OPTION] [SET1] [SET2]'''


SET1 denotes what we wish to translate in the input file, and SET2 means what we want to convert SET1 as the output of the translation. So the sets can be a single character or multiple characters.
SET1 denotes what we wish to translate in the input file, and SET2 means what we want to convert SET1 as the output of the translation. So the sets can be a single character or multiple characters.
Zeile 421: Zeile 421:
'''Example1:''' Suppose you just want to replace a in “sahil suri” with b we can use tr sets. We use [https://www.linuxnix.com/9-linux-echo-command-examples/ echo command] to send “sahil suri” to tr command. The tr command by default is not able to read data stream. We use [https://www.linuxnix.com/linuxunix-redirection-operatorsfile-descriptors-explained-examples/ Linux inbuilt redirection operators] to feed data to tr command.
'''Example1:''' Suppose you just want to replace a in “sahil suri” with b we can use tr sets. We use [https://www.linuxnix.com/9-linux-echo-command-examples/ echo command] to send “sahil suri” to tr command. The tr command by default is not able to read data stream. We use [https://www.linuxnix.com/linuxunix-redirection-operatorsfile-descriptors-explained-examples/ Linux inbuilt redirection operators] to feed data to tr command.


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'a' 'b'
'''echo "sahil suri" | tr 'a' 'b'
  sbhil suri'''</div>
  sbhil suri'''


'''Example2:''' Suppose if you want to replace multiple characters one after the other then we can use below-set examples. Suppose you want to replace a with b, r with x and i with z, below is the case you are looking at.
'''Example2:''' Suppose if you want to replace multiple characters one after the other then we can use below-set examples. Suppose you want to replace a with b, r with x and i with z, below is the case you are looking at.


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'ari' 'bxz'
'''echo "sahil suri" | tr 'ari' 'bxz'
  sbhzl suxz'''</div>
  sbhzl suxz'''


'''Note:''' Make sure that first set and second set have the same number of characters. For example,&nbsp; i is just replaced with z as we don’t have the third character on the list below.
'''Note:''' Make sure that first set and second set have the same number of characters. For example,&nbsp; i is just replaced with z as we don’t have the third character on the list below.


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'ari' 'bz'
'''echo "sahil suri" | tr 'ari' 'bz'
  sbhzl suzz'''</div>
  sbhzl suzz'''


Similarly, we can use sets to convert multiple letters. Some of the sets tr supports are as below.
Similarly, we can use sets to convert multiple letters. Some of the sets tr supports are as below.


=== {{anchor|RefHeadingToc6951523260012}} POSIX Character set  ===
=== POSIX Character set  ===


<div style="margin-left:0cm;margin-right:0cm;">'''[:digit:] Only the digits 0 to 9
'''[:digit:] Only the digits 0 to 9
  [:alnum:] Any alphanumeric character
  [:alnum:] Any alphanumeric character
  [:alpha:] Any alpha character A to Z or a to z.
  [:alpha:] Any alpha character A to Z or a to z.
Zeile 449: Zeile 449:
  [:upper:] Any alpha character A to Z.
  [:upper:] Any alpha character A to Z.
  [:lower:] Any alpha character a to z.
  [:lower:] Any alpha character a to z.
  [:cntrl:] Control Characters NL CR LF TAB VT FF NUL SOH STX EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL.'''</div>
  [:cntrl:] Control Characters NL CR LF TAB VT FF NUL SOH STX EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL.'''


=== {{anchor|RefHeadingToc6971523260012}} Character sets ===
=== Character sets ===


# '''a-z To represent complete lower case alphabets'''  
# '''a-z To represent complete lower case alphabets'''  
Zeile 459: Zeile 459:




=== {{anchor|RefHeadingToc32401523260012}} lower to upper case. ===
=== lower to upper case. ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'a-z' 'A-Z'
'''echo "sahil suri" | tr 'a-z' 'A-Z'
  SAHIL SURI'''</div>
  SAHIL SURI'''


The tr command mentioned above implies to translate all alphabets in lowercase denoted by ‘a-z’ into alphabets in upper case denoted by ‘A-Z’
The tr command mentioned above implies to translate all alphabets in lowercase denoted by ‘a-z’ into alphabets in upper case denoted by ‘A-Z’


=== {{anchor|RefHeadingToc32421523260012}} Convert all characters in input from upper to lower case ===
=== Convert all characters in input from upper to lower case ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "SAHIL SURI" | tr 'A-Z' 'a-z'
'''echo "SAHIL SURI" | tr 'A-Z' 'a-z'
  sahil suri'''</div>
  sahil suri'''


=== {{anchor|RefHeadingToc32441523260012}} Translate only particular characters from lower to upper case ===
=== Translate only particular characters from lower to upper case ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'shlr' 'SHLR'
'''echo "sahil suri" | tr 'shlr' 'SHLR'
  SaHiL SuRi'''</div>
  SaHiL SuRi'''


In the previous two examples, we gave ranges, but we can use distinct characters as well as shown in the above example.
In the previous two examples, we gave ranges, but we can use distinct characters as well as shown in the above example.


=== {{anchor|RefHeadingToc32461523260012}} Use multiple ranges  ===
=== Use multiple ranges  ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "sahil suri" | tr 'a-dr-z' 'A-DR-Z'
'''echo "sahil suri" | tr 'a-dr-z' 'A-DR-Z'
  SAhil SURi'''</div>
  SAhil SURi'''


=== {{anchor|RefHeadingToc32481523260012}} translate individual characters as well ===
=== translate individual characters as well ===


==== Translate braces into parenthesis ====
==== Translate braces into parenthesis ====


<div style="margin-left:0cm;margin-right:0cm;">'''echo "{ Hello World }" > infile'''  
'''echo "{ Hello World }" > infile'''  
  '''tr '{}' '()' < infile > outfile'''  
  '''tr '{}' '()' < infile > outfile'''  
  '''cat outfile'''  
  '''cat outfile'''  
  '''( Hello World )'''</div>
  '''( Hello World )'''


=== {{anchor|RefHeadingToc32501523260012}} Translate spaces to new lines.  ===
=== Translate spaces to new lines.  ===


We use infile as our test file. Use [https://www.linuxnix.com/20-linuxunix-cat-command-examples/ cat command] to display the content of the file.
We use infile as our test file. Use [https://www.linuxnix.com/20-linuxunix-cat-command-examples/ cat command] to display the content of the file.
Zeile 509: Zeile 509:
While using translate, you may use ” ” or [:space:] to represent white space. I find the first option easier to type.
While using translate, you may use ” ” or [:space:] to represent white space. I find the first option easier to type.


=== {{anchor|RefHeadingToc32521523260012}} Replace white space ===
=== Replace white space ===


'''cat infile | tr " " ":"
'''cat infile | tr " " ":"
Zeile 516: Zeile 516:
  solaris|linux|aix'''
  solaris|linux|aix'''


=== {{anchor|RefHeadingToc33941523260012}} Replace multiple occurrences ===
=== Replace multiple occurrences ===


==== ... with a single appearance of the character.  ====
==== ... with a single appearance of the character.  ====
Zeile 529: Zeile 529:
In the above case, we used the tr command with -s option to indicate a squeeze operation.This replaces multiple occurrences of a character with a single appearance of the same character.
In the above case, we used the tr command with -s option to indicate a squeeze operation.This replaces multiple occurrences of a character with a single appearance of the same character.


==== {{anchor|RefHeadingToc32561523260012}} … with a different character ====
==== … with a different character ====


'''cat infile
'''cat infile
Zeile 538: Zeile 538:
The above tr command squeezes multiple occurrences of white space into one semicolon character.
The above tr command squeezes multiple occurrences of white space into one semicolon character.


=== {{anchor|RefHeadingToc32581523260012}} Delete all occurances of a character. ===
=== Delete all occurances of a character. ===


To delete occurrences of a character we use the -d option with the tr command followed by the character to be removed.
To delete occurrences of a character we use the -d option with the tr command followed by the character to be removed.


<div style="margin-left:0cm;margin-right:0cm;">'''echo "linuxunix" | tr -d 'u'
'''echo "linuxunix" | tr -d 'u'
  linxnix'''</div>
  linxnix'''


The above command removes all occurrences of the '''character u''' from the input string.
The above command removes all occurrences of the '''character u''' from the input string.


=== {{anchor|RefHeadingToc32601523260012}} Remove all digits from the input. ===
=== Remove all digits from the input. ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "james bond 007" | tr -d '0-9'
'''echo "james bond 007" | tr -d '0-9'
  james bond'''</div>
  james bond'''


=== {{anchor|RefHeadingToc41681523260012}} Remove all alphabets from the input. ===
=== Remove all alphabets from the input. ===


<div style="margin-left:0cm;margin-right:0cm;">'''echo "james bond 007" | tr -d 'a-zA-Z'
'''echo "james bond 007" | tr -d 'a-zA-Z'
  007'''</div>
  007'''


=== {{anchor|RefHeadingToc32621523260012}} Remove characters except the given ===
=== Remove characters except the given ===


We used -d option to delete characters we mentioned from the input. We may use the -c option with the -d option to delete all characters except those that we mention.
We used -d option to delete characters we mentioned from the input. We may use the -c option with the -d option to delete all characters except those that we mention.


<div style="margin-left:0cm;margin-right:0cm;">'''echo "solaris linux hp-ux" | tr -cd 'slh'
'''echo "solaris linux hp-ux" | tr -cd 'slh'
  slslh'''</div>
  slslh'''


The above tr command removed all characters including the new line leaving behind the characters s,l and h which we mentioned to be removed. Using the -c option is also sometimes referred to as complimenting the set.
The above tr command removed all characters including the new line leaving behind the characters s,l and h which we mentioned to be removed. Using the -c option is also sometimes referred to as complimenting the set.


=== {{anchor|RefHeadingToc32641523260012}} Remove all non-alphanumeric and space ===
=== Remove all non-alphanumeric and space ===


'''echo "solaris | linux 007 ; hp-ux :::: aix" | tr -cd "[:alpha:][:space:][:digit:]"
'''echo "solaris | linux 007 ; hp-ux :::: aix" | tr -cd "[:alpha:][:space:][:digit:]"
Zeile 573: Zeile 573:
This example could prove to be especially useful when dealing with a file having a lot of junk characters.
This example could prove to be especially useful when dealing with a file having a lot of junk characters.


=== {{anchor|RefHeadingToc32661523260012}} Translate non-alphanumeric characters  ===
=== Translate non-alphanumeric characters  ===


==== into a single newline character ====
==== into a single newline character ====


<div style="margin-left:0cm;margin-right:0cm;">'''echo "james bond 007" | tr -cs 'a-zA-Z0-9' '\n'
'''echo "james bond 007" | tr -cs 'a-zA-Z0-9' '\n'
  james
  james
  bond
  bond
  007'''</div>
  007'''


=== {{anchor|RefHeadingToc32681523260012}} Join lines in a file into a single ===
=== Join lines in a file into a single ===


'''cat infile
'''cat infile
Zeile 595: Zeile 595:
This concludes our exploration of the tr command. Please consider reading our articles about&nbsp;[https://www.linuxnix.com/category/Programming/Sed/ sed]&nbsp;which is another utility that provides most of the translation features we discussed in the above examples and a lot more.
This concludes our exploration of the tr command. Please consider reading our articles about&nbsp;[https://www.linuxnix.com/category/Programming/Sed/ sed]&nbsp;which is another utility that provides most of the translation features we discussed in the above examples and a lot more.


== {{anchor|RefHeadingToc6991523260012}} Linux tr command ==
== Linux tr command ==


On [https://www.computerhope.com/jargon/u/unix-like.htm Unix-like] operating systems, the '''tr''' command automatically translates (substitutes, or maps) one set of [https://www.computerhope.com/jargon/c/charact.htm characters] to another.
On [https://www.computerhope.com/jargon/u/unix-like.htm Unix-like] operating systems, the '''tr''' command automatically translates (substitutes, or maps) one set of [https://www.computerhope.com/jargon/c/charact.htm characters] to another.
Zeile 603: Zeile 603:
The '''tr''' utility copies the [https://www.computerhope.com/jargon/s/stdin.htm standard input] to the standard output with substitution or deletion of selected characters.
The '''tr''' utility copies the [https://www.computerhope.com/jargon/s/stdin.htm standard input] to the standard output with substitution or deletion of selected characters.


=== {{anchor|RefHeadingToc7031523260012}} Syntax ===
=== Syntax ===


<div style="margin-left:0cm;margin-right:0cm;">tr [-Ccsu] ''string1'' ''string2''</div>
tr [-Ccsu] ''string1'' ''string2''


In this form, the characters in the [https://www.computerhope.com/jargon/s/string.htm string] ''string1'' are translated into the characters in ''string2'' where the first character in ''string1'' is translated into the first character in ''string2'' and so on. If ''string1'' is longer than ''string2'', the last character found in ''string2'' is duplicated until string1 is exhausted.
In this form, the characters in the [https://www.computerhope.com/jargon/s/string.htm string] ''string1'' are translated into the characters in ''string2'' where the first character in ''string1'' is translated into the first character in ''string2'' and so on. If ''string1'' is longer than ''string2'', the last character found in ''string2'' is duplicated until string1 is exhausted.


<div style="margin-left:0cm;margin-right:0cm;">tr [-Ccu] -d ''string1''</div>
tr [-Ccu] -d ''string1''


In this form, the characters in ''string1'' are deleted from the input.
In this form, the characters in ''string1'' are deleted from the input.


<div style="margin-left:0cm;margin-right:0cm;">tr [-Ccu] -s ''string1''</div>
tr [-Ccu] -s ''string1''


In this form, the characters in ''string1'' are compressed as described for the '''-s''' option (see below).
In this form, the characters in ''string1'' are compressed as described for the '''-s''' option (see below).


<div style="margin-left:0cm;margin-right:0cm;">tr [-Ccu] -ds ''string1'' ''string2''</div>
tr [-Ccu] -ds ''string1'' ''string2''


In the fourth form, the characters in ''string1'' are deleted from the input, and the characters in ''string2'' are compressed as described for the '''-s''' option.
In the fourth form, the characters in ''string1'' are deleted from the input, and the characters in ''string2'' are compressed as described for the '''-s''' option.


=== {{anchor|RefHeadingToc7051523260012}} Options ===
=== Options ===




{| style="border-spacing:0;margin:auto;width:17.501cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
|| '''-C'''
|| '''-C'''
|| Complement the set of characters in ''string1'', that is "'''-C ab'''" includes every character except for ''''a'''' and ''''b''''.
|| Complement the set of characters in ''string1'', that is "'''-C ab'''" includes every character except for ''''a'''' and ''''b''''.
|- style="border:none;padding:0.049cm;"
|-  
|| '''-c'''
|| '''-c'''
|| Same as '''-C''' but complement the set of values in ''string1''.
|| Same as '''-C''' but complement the set of values in ''string1''.
|- style="border:none;padding:0.049cm;"
|-  
|| '''-d'''
|| '''-d'''
|| Delete characters in ''string1'' from the input.
|| Delete characters in ''string1'' from the input.
|- style="border:none;padding:0.049cm;"
|-  
|| '''-s'''
|| '''-s'''
|| Squeeze multiple occurrences of the characters listed in the last operand (either ''string1'' or ''string2'') in the input into a single instance of the character. This occurs after all deletion and translation is completed.
|| Squeeze multiple occurrences of the characters listed in the last operand (either ''string1'' or ''string2'') in the input into a single instance of the character. This occurs after all deletion and translation is completed.
|- style="border:none;padding:0.049cm;"
|-  
|| '''-u'''
|| '''-u'''
|| Guarantee that any output is unbuffered.
|| Guarantee that any output is unbuffered.
Zeile 644: Zeile 644:
|-
|-
|}
|}
=== {{anchor|RefHeadingToc7071523260012}} How Characters Are Specified ===
=== How Characters Are Specified ===


When specifying the characters to translate with '''tr''', the following conventions are used to represent sets (or "classes") of characters.
When specifying the characters to translate with '''tr''', the following conventions are used to represent sets (or "classes") of characters.
Zeile 651: Zeile 651:




{| style="border-spacing:0;margin:auto;width:17.501cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
|| '''\'''''octal''
|| '''\'''''octal''
|| A backslash followed by 1, 2 or 3 [https://www.computerhope.com/jargon/o/octal.htm octal] digits represents a character with that encoded value. To follow an octal sequence with a digit as a character, pad the octal sequence on the left with zeroes.
|| A backslash followed by 1, 2 or 3 [https://www.computerhope.com/jargon/o/octal.htm octal] digits represents a character with that encoded value. To follow an octal sequence with a digit as a character, pad the octal sequence on the left with zeroes.
|- style="border:none;padding:0.049cm;"
|-  
|| '''\'''''character''
|| '''\'''''character''
|| A backslash followed by certain special characters maps to special values:
|| A backslash followed by certain special characters maps to special values:




{| style="border-spacing:0;margin:auto;width:15.797cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
|| '''\a'''
|| '''\a'''
|| The "alert" character, which issues a notification or alert to the terminal.
|| The "alert" character, which issues a notification or alert to the terminal.
|- style="border:none;padding:0.049cm;"
|-  
|| '''\b'''
|| '''\b'''
|| Backspace.
|| Backspace.
|- style="border:none;padding:0.049cm;"
|-  
|| '''\f'''
|| '''\f'''
|| [https://www.computerhope.com/jargon/f/formfeed.htm Form feed].
|| [https://www.computerhope.com/jargon/f/formfeed.htm Form feed].
|- style="border:none;padding:0.049cm;"
|-  
|| '''\n'''
|| '''\n'''
|| [https://www.computerhope.com/jargon/n/newline.htm Newline].
|| [https://www.computerhope.com/jargon/n/newline.htm Newline].
|- style="border:none;padding:0.049cm;"
|-  
|| '''\r'''
|| '''\r'''
|| [https://www.computerhope.com/jargon/c/cr.htm Carriage return].
|| [https://www.computerhope.com/jargon/c/cr.htm Carriage return].
|- style="border:none;padding:0.049cm;"
|-  
|| '''\t'''
|| '''\t'''
|| [https://www.computerhope.com/jargon/t/tab.htm Tab].
|| [https://www.computerhope.com/jargon/t/tab.htm Tab].
|- style="border:none;padding:0.049cm;"
|-  
|| '''\v'''
|| '''\v'''
|| Vertical tab.
|| Vertical tab.
Zeile 685: Zeile 685:
|}
|}
A backslash followed by any other character maps to that character.  
A backslash followed by any other character maps to that character.  
|- style="border:none;padding:0.049cm;"
|-  
|| ''c'''''-'''''c''
|| ''c'''''-'''''c''
|| Character [https://www.computerhope.com/jargon/r/range.htm range]. For non-octal range endpoints represents the range of characters between the range endpoints, inclusive and in ascending order, as defined by the collation sequence. If either or both of the range endpoints are octal sequences, it represents the range of specific coded values between the range endpoints, inclusive.
|| Character [https://www.computerhope.com/jargon/r/range.htm range]. For non-octal range endpoints represents the range of characters between the range endpoints, inclusive and in ascending order, as defined by the collation sequence. If either or both of the range endpoints are octal sequences, it represents the range of specific coded values between the range endpoints, inclusive.
|- style="border:none;padding:0.049cm;"
|-  
|| '''[:'''''class''''':]'''
|| '''[:'''''class''''':]'''
|| Represents all characters belonging to the defined character class. Class names are:
|| Represents all characters belonging to the defined character class. Class names are:




{| style="border-spacing:0;width:7.137cm;"
{| class="wikitable sortable"
|- style="border:none;padding:0.049cm;"
|-  
|| '''alnum'''
|| '''alnum'''
|| [https://www.computerhope.com/jargon/a/alphanum.htm Alphanumeric] characters.
|| [https://www.computerhope.com/jargon/a/alphanum.htm Alphanumeric] characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''alpha'''
|| '''alpha'''
|| Alphabetic characters.
|| Alphabetic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''blank'''
|| '''blank'''
|| [https://www.computerhope.com/jargon/w/whitspac.htm White space] characters.
|| [https://www.computerhope.com/jargon/w/whitspac.htm White space] characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''cntrl'''
|| '''cntrl'''
|| Control characters.
|| Control characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''digit'''
|| '''digit'''
|| Numeric characters.
|| Numeric characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''graph'''
|| '''graph'''
|| Graphic characters.
|| Graphic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''ideogram'''
|| '''ideogram'''
|| Ideographic characters.
|| Ideographic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''lower'''
|| '''lower'''
|| [https://www.computerhope.com/jargon/l/lowercas.htm Lowercase] alphabetic characters.
|| [https://www.computerhope.com/jargon/l/lowercas.htm Lowercase] alphabetic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''phonogram'''
|| '''phonogram'''
|| Phonographic characters.
|| Phonographic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''print'''
|| '''print'''
|| Printable characters.
|| Printable characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''punct'''
|| '''punct'''
|| Punctuation characters.
|| Punctuation characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''rune'''
|| '''rune'''
|| Valid characters.
|| Valid characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''space'''
|| '''space'''
|| Space characters.
|| Space characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''special'''
|| '''special'''
|| Special characters.
|| Special characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''upper'''
|| '''upper'''
|| [https://www.computerhope.com/jargon/u/uppercase.htm Uppercase] alphabetic characters.
|| [https://www.computerhope.com/jargon/u/uppercase.htm Uppercase] alphabetic characters.
|- style="border:none;padding:0.049cm;"
|-  
|| '''xdigit'''
|| '''xdigit'''
|| [https://www.computerhope.com/jargon/h/hex.htm Hexadecimal] characters.
|| [https://www.computerhope.com/jargon/h/hex.htm Hexadecimal] characters.
Zeile 745: Zeile 745:
|}
|}
When "'''[:lower:]'''" appears in ''string1'' and "'''[:upper:]'''" appears in the same relative position in ''string2'', it represents the characters pairs from the toupper mapping in the '''LC_CTYPE''' category of the current locale. When "'''[:upper:]'''" appears in ''string1'' and "'''[:lower:]'''" appears in the same relative position in ''string2'', it represents the characters pairs from the '''tolower''' mapping in the '''LC_CTYPE''' category of the current locale.With the exception of case conversion, characters in the classes are in unspecified order.For specific information as to which [https://www.computerhope.com/jargon/a/ascii.htm ASCII] characters are included in these classes, see '''ctype''' and related manual pages."'''[=equiv=]'''" Represents all characters belonging to the same equivalence class as '''equiv''', ordered by their encoded values.  
When "'''[:lower:]'''" appears in ''string1'' and "'''[:upper:]'''" appears in the same relative position in ''string2'', it represents the characters pairs from the toupper mapping in the '''LC_CTYPE''' category of the current locale. When "'''[:upper:]'''" appears in ''string1'' and "'''[:lower:]'''" appears in the same relative position in ''string2'', it represents the characters pairs from the '''tolower''' mapping in the '''LC_CTYPE''' category of the current locale.With the exception of case conversion, characters in the classes are in unspecified order.For specific information as to which [https://www.computerhope.com/jargon/a/ascii.htm ASCII] characters are included in these classes, see '''ctype''' and related manual pages."'''[=equiv=]'''" Represents all characters belonging to the same equivalence class as '''equiv''', ordered by their encoded values.  
|- style="border:none;padding:0.049cm;"
|-  
|| '''['''''<nowiki>#</nowiki>'''''<nowiki>*</nowiki>'''''n''''']'''
|| '''['''''<nowiki>#</nowiki>'''''<nowiki>*</nowiki>'''''n''''']'''
|| Represents ''n'' repeated occurrences of the character represented by ''<nowiki>#</nowiki>''. This expression is only valid when it occurs in ''string2''. If ''n'' is omitted, or is zero, it is be interpreted as large enough to extend ''string2'' sequence to the length of ''string1''. If ''n'' has a leading zero, it is interpreted as an octal value, otherwise, it is interpreted as a decimal value.
|| Represents ''n'' repeated occurrences of the character represented by ''<nowiki>#</nowiki>''. This expression is only valid when it occurs in ''string2''. If ''n'' is omitted, or is zero, it is be interpreted as large enough to extend ''string2'' sequence to the length of ''string1''. If ''n'' has a leading zero, it is interpreted as an octal value, otherwise, it is interpreted as a decimal value.
Zeile 752: Zeile 752:
|-
|-
|}
|}
=== {{anchor|RefHeadingToc7091523260012}} Environment ===
=== Environment ===


The '''LANG''', '''LC_ALL''', '''LC_CTYPE''' and '''LC_COLLATE''' [https://www.computerhope.com/jargon/e/envivari.htm environment variables] affect the execution of '''tr'''.
The '''LANG''', '''LC_ALL''', '''LC_CTYPE''' and '''LC_COLLATE''' [https://www.computerhope.com/jargon/e/envivari.htm environment variables] affect the execution of '''tr'''.


=== {{anchor|RefHeadingToc7111523260012}} Exit Status ===
=== Exit Status ===


'''tr''' returns an exit status of '''0''' if it operated successfully, and a value greater than zero if an error occurred.
'''tr''' returns an exit status of '''0''' if it operated successfully, and a value greater than zero if an error occurred.


=== {{anchor|RefHeadingToc7131523260012}} Examples ===
=== Examples ===


<div style="margin-left:0cm;margin-right:0cm;">tr -cs "[:alpha:]" "\n" < file1</div>
tr -cs "[:alpha:]" "\n" < file1


Create a list of the words in '''file1''', one per line, where a word is taken to be a maximal string of letters.
Create a list of the words in '''file1''', one per line, where a word is taken to be a maximal string of letters.


<div style="margin-left:0cm;margin-right:0cm;">tr "[:lower:]" "[:upper:]" < file1</div>
tr "[:lower:]" "[:upper:]" < file1


Translate the contents of '''file1''' to uppercase.
Translate the contents of '''file1''' to uppercase.


<div style="margin-left:0cm;margin-right:0cm;">tr -cd "[:print:]" < file1</div>
tr -cd "[:print:]" < file1


Remove all non-printable characters from '''file1'''.
Remove all non-printable characters from '''file1'''.


<div style="margin-left:0cm;margin-right:0cm;">tr "[=e=]" "e"</div>
tr "[=e=]" "e"


Remove all "diacritical" marks from accented versions of the letter '''e'''.
Remove all "diacritical" marks from accented versions of the letter '''e'''.


== {{anchor|RefHeadingToc7151523260012}} tr examples ==
== tr examples ==


The tr command in UNIX is a command line utility for translating or deleting characters. It supports a range of transformations including uppercase to lowercase, squeezing repeating characters, deleting specific characters and basic find and replace. It can be used with UNIX pipes to support more complex translation. '''tr stands for translate.'''
The tr command in UNIX is a command line utility for translating or deleting characters. It supports a range of transformations including uppercase to lowercase, squeezing repeating characters, deleting specific characters and basic find and replace. It can be used with UNIX pipes to support more complex translation. '''tr stands for translate.'''
Zeile 784: Zeile 784:
'''Syntax :'''
'''Syntax :'''


<div style="margin-left:0cm;margin-right:0cm;">'''$ tr [OPTION] SET1 [SET2]'''</div>
'''$ tr [OPTION] SET1 [SET2]'''


'''Options'''
'''Options'''


<div style="margin-left:0cm;margin-right:0cm;">-c : complements the set of characters in string.i.e., operations apply to characters not in the given set
-c : complements the set of characters in string.i.e., operations apply to characters not in the given set
  -d : delete characters in the first set from the output.
  -d : delete characters in the first set from the output.
  -s : replaces repeated characters listed in the set1 with single occurrence
  -s : replaces repeated characters listed in the set1 with single occurrence
  -t : truncates set1</div>
  -t : truncates set1


=== {{anchor|RefHeadingToc21721523260012}} Convert lower case to upper case ===
=== Convert lower case to upper case ===


To convert from lower case to upper case the predefined sets in tr can be used.  
To convert from lower case to upper case the predefined sets in tr can be used.  


<div style="margin-left:0cm;margin-right:0cm;">'''$cat greekfile'''</div>
'''$cat greekfile'''


Output:
Output:


<div style="margin-left:0cm;margin-right:0cm;">WELCOME TO  
WELCOME TO  
  GeeksforGeeks</div>
  GeeksforGeeks
<div style="margin-left:0cm;margin-right:0cm;">'''$cat greekfile | tr “[a-z]” “[A-Z]”'''</div>
'''$cat greekfile | tr “[a-z]” “[A-Z]”'''


Output:
Output:


<div style="margin-left:0cm;margin-right:0cm;">WELCOME TO
WELCOME TO
  GEEKSFORGEEKS</div>
  GEEKSFORGEEKS


or
or


<div style="margin-left:0cm;margin-right:0cm;">'''$cat geekfile | tr “[:lower:]” “[:upper:]”'''</div>
'''$cat geekfile | tr “[:lower:]” “[:upper:]”'''


Output:
Output:


<div style="margin-left:0cm;margin-right:0cm;">WELCOME TO
WELCOME TO
  GEEKSFORGEEKS</div>
  GEEKSFORGEEKS


=== {{anchor|RefHeadingToc21741523260012}} Translate white-space to tabs ===
=== Translate white-space to tabs ===


The following command will translate all the white-space to tabs
The following command will translate all the white-space to tabs


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "Welcome To GeeksforGeeks" | tr [:space:] '\t''''</div>
'''$ echo "Welcome To GeeksforGeeks" | tr [:space:] '\t''''


Output:
Output:


<div style="margin-left:0cm;margin-right:0cm;">Welcome    To    GeeksforGeeks    </div>
Welcome    To    GeeksforGeeks     


=== {{anchor|RefHeadingToc21761523260012}} Translate braces into parenthesis ===
=== Translate braces into parenthesis ===


You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.
You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.


'''$cat greekfile'''
'''$cat greekfile'''
   {WELCOME TO}  
   {WELCOME TO}  
  GeeksforGeeks
  GeeksforGeeks
'''$ tr '{}' '()'  newfile.txt'''
'''$ tr '{}' '()'  newfile.txt'''
  (WELCOME TO)  
  (WELCOME TO)  
  GeeksforGeeks
  GeeksforGeeks
Zeile 842: Zeile 842:
The above command will read each character from “geekfile.txt”, translate if it is a brace, and write the output in “newfile.txt”.
The above command will read each character from “geekfile.txt”, translate if it is a brace, and write the output in “newfile.txt”.


=== {{anchor|RefHeadingToc21781523260012}} Squeeze repetition  ===
=== Squeeze repetition  ===


To squeeze repeat occurrences of characters specified in a set use the -s option. This removes repeated instances of a character.OR we can say that,you can convert multiple continuous spaces with a single space  
To squeeze repeat occurrences of characters specified in a set use the -s option. This removes repeated instances of a character.OR we can say that,you can convert multiple continuous spaces with a single space  


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "Welcome    To    GeeksforGeeks" | tr -s [:space:] ' ''''
'''$ echo "Welcome    To    GeeksforGeeks" | tr -s [:space:] ' ''''
  Welcome To GeeksforGeeks</div>
  Welcome To GeeksforGeeks


=== {{anchor|RefHeadingToc21801523260012}} Delete specified characters  ===
=== Delete specified characters  ===


To delete specific characters use the -d option.This option deletes characters in the first set specified.
To delete specific characters use the -d option.This option deletes characters in the first set specified.


'''$ echo "Welcome To GeeksforGeeks" | tr -d 'w''''
'''$ echo "Welcome To GeeksforGeeks" | tr -d 'w''''
  elcome To GeeksforGeeks
  elcome To GeeksforGeeks


=== {{anchor|RefHeadingToc21821523260012}} Remove all the digits from the string, use ===
=== Remove all the digits from the string, use ===


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "my ID is 73535" | tr -d [:digit:]'''
'''$ echo "my ID is 73535" | tr -d [:digit:]'''
  my ID is</div>
  my ID is


=== {{anchor|RefHeadingToc21841523260012}} Complement the sets using -c option ===
=== Complement the sets using -c option ===


You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.
You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "my ID is 73535" | tr -cd [:digit:]'''
'''$ echo "my ID is 73535" | tr -cd [:digit:]'''
  73535</div>
  73535


Or
Or


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo “unix” | tr –c “u” “a”'''
'''$ echo “unix” | tr –c “u” “a”'''
  Uaaa</div>
  Uaaa


=== {{anchor|RefHeadingToc7171523260012}} tr Examples ===
=== tr Examples ===


'''tr''' (short for '''translate''') is a useful command line utility that translates and/or deletes characters from stdin input, and writes to stdout. It is a useful program for manipulating text on the command line.
'''tr''' (short for '''translate''') is a useful command line utility that translates and/or deletes characters from stdin input, and writes to stdout. It is a useful program for manipulating text on the command line.
Zeile 879: Zeile 879:
The syntax for running '''tr command''' is as follows, where characters in '''SET1''' are translated to characters in '''SET2'''.
The syntax for running '''tr command''' is as follows, where characters in '''SET1''' are translated to characters in '''SET2'''.


<div style="margin-left:0cm;margin-right:0cm;">$ tr flags [SET1] [SET2]</div>
$ tr flags [SET1] [SET2]


==== {{anchor|RefHeadingToc39001523260012}} 1. A simple tr command ====
==== 1. A simple tr command ====


Use case is to change all lower case letters in text to upper case and vice versa, as shown below.
Use case is to change all lower case letters in text to upper case and vice versa, as shown below.


<div style="margin-left:0cm;margin-right:0cm;">'''$ cat linux.txt
'''$ cat linux.txt
  linux is my life
  linux is my life
  linux has changed my life
  linux has changed my life
  linux is best and everthing to me..:)'''</div>
  linux is best and everthing to me..:)'''
<div style="margin-left:0cm;margin-right:0cm;">'''$ cat domains.txt | tr [:lower:] [:upper:]
'''$ cat domains.txt | tr [:lower:] [:upper:]
  LINUX IS MY LIFE
  LINUX IS MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX IS BEST AND EVERTHING TO ME..:)'''</div>
  LINUX IS BEST AND EVERTHING TO ME..:)'''


==== {{anchor|RefHeadingToc39021523260012}} Alternatively ====
==== Alternatively ====


you can use the following command to change all lower case letters to upper case in a file as shown.
you can use the following command to change all lower case letters to upper case in a file as shown.


<div style="margin-left:0cm;margin-right:0cm;">'''$ cat linux.txt | tr [a-z] [A-Z]
'''$ cat linux.txt | tr [a-z] [A-Z]
  LINUX IS MY LIFE
  LINUX IS MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX IS BEST AND EVERTHING TO ME..:)'''</div>
  LINUX IS BEST AND EVERTHING TO ME..:)'''


==== {{anchor|RefHeadingToc39041523260012}} To save the results ====
==== To save the results ====


written to '''stdout''' in a file for later processing, use the shell’s output redirection feature <tt>(>)</tt> as shown.
written to '''stdout''' in a file for later processing, use the shell’s output redirection feature <tt>(>)</tt> as shown.


<div style="margin-left:0cm;margin-right:0cm;">'''$ cat linux.txt | tr [a-z] [A-Z] >output.txt
'''$ cat linux.txt | tr [a-z] [A-Z] >output.txt
  $ cat output.txt'''  
  $ cat output.txt'''  
  '''LINUX IS MY LIFE
  '''LINUX IS MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX HAS CHANGED MY LIFE
  LINUX IS BEST AND EVERTHING TO ME..:)'''</div>
  LINUX IS BEST AND EVERTHING TO ME..:)'''


==== {{anchor|RefHeadingToc39061523260012}} In regards to the redirection ====
==== In regards to the redirection ====


you can send input to '''tr''' using the input redirection and redirect the output to a file using the same command, as shown.
you can send input to '''tr''' using the input redirection and redirect the output to a file using the same command, as shown.


<div style="margin-left:0cm;margin-right:0cm;">'''$ tr [a-z] [A-Z] < linux.txt >output.txt'''</div>
'''$ tr [a-z] [A-Z] < linux.txt >output.txt'''


==== {{anchor|RefHeadingToc39081523260012}} Another useful feature ====
==== Another useful feature ====


you can use the <tt>-d</tt> flag to delete characters, for example to remove the spaces in the domain names using the following command.
you can use the <tt>-d</tt> flag to delete characters, for example to remove the spaces in the domain names using the following command.


'''$ cat domains.txt
'''$ cat domains.txt
  www. tecmint. Com
  www. tecmint. Com
  www. fossmint. Com
  www. fossmint. Com
  www. linuxsay. Com'''
  www. linuxsay. Com'''
'''$ cat domains.txt | tr -d '''''  
'''$ cat domains.txt | tr -d '''''  
  [http://www.tecmint.com/ www.tecmint.com]
  [http://www.tecmint.com/ www.tecmint.com]
  [http://www.fossmint.com/ www.fossmint.com]
  [http://www.fossmint.com/ www.fossmint.com]
  www.linuxsay.com'''
  www.linuxsay.com'''


==== {{anchor|RefHeadingToc39101523260012}} If there are repeated characters in a sequence ====
==== If there are repeated characters in a sequence ====


(for instance double spaces) in the text you are processing, you can use the <tt>-s</tt> option to squeeze the characters leaving only one occurrence of it.
(for instance double spaces) in the text you are processing, you can use the <tt>-s</tt> option to squeeze the characters leaving only one occurrence of it.


'''$ cat domains.txt
'''$ cat domains.txt
  www.tecmint.....com
  www.tecmint.....com
  [http://www.fossmint.com/ www.fossmint.com]
  [http://www.fossmint.com/ www.fossmint.com]
  [http://www.linuxsay.com/ www.linuxsay.com]
  [http://www.linuxsay.com/ www.linuxsay.com]
'''$ cat domains.txt | tr -s '''''  
'''$ cat domains.txt | tr -s '''''  
  [http://www.tecmint.com/ www.tecmint.com]
  [http://www.tecmint.com/ www.tecmint.com]
  [http://www.fossmint.com/ www.fossmint.com]
  [http://www.fossmint.com/ www.fossmint.com]
  www.linuxsay.com'''
  www.linuxsay.com'''


==== {{anchor|RefHeadingToc39121523260012}} The -c option ====
==== The -c option ====


tells '''tr''' to use the complement in the given of '''SET'''. In this example, we want to delete all the letters and only leave the '''UID'''.
tells '''tr''' to use the complement in the given of '''SET'''. In this example, we want to delete all the letters and only leave the '''UID'''.


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "My UID is $UID" | tr -cd "[:digit:]\n"'''
'''$ echo "My UID is $UID" | tr -cd "[:digit:]\n"'''
  OR
  OR
  '''$ echo "My UID is $UID" | tr -d "a-zA-Z"'''</div>
  '''$ echo "My UID is $UID" | tr -d "a-zA-Z"'''


==== {{anchor|RefHeadingToc39141523260012}} Here is an example of breaking a single line ====
==== Here is an example of breaking a single line ====


of words (sentence) into multiple lines, where each word appears in a separate line.
of words (sentence) into multiple lines, where each word appears in a separate line.


'''$ echo "My UID is $UID"
'''$ echo "My UID is $UID"
  My UID is 1000'''
  My UID is 1000'''
'''$ echo "My UID is $UID" | tr " "  "\n"
'''$ echo "My UID is $UID" | tr " "  "\n"
  My  
  My  
  UID  
  UID  
Zeile 965: Zeile 965:
  1000'''
  1000'''


==== {{anchor|RefHeadingToc39161523260012}} Related to the previous example ====
==== Related to the previous example ====


you can also translate multiple lines of words into a single sentence as shown.
you can also translate multiple lines of words into a single sentence as shown.


'''$ cat uid.txt
'''$ cat uid.txt
  My  
  My  
  UID  
  UID  
  is  
  is  
  1000'''
  1000'''
'''$ tr "\n" " " < uid.txt
'''$ tr "\n" " " < uid.txt
  My UID is 1000'''
  My UID is 1000'''


==== {{anchor|RefHeadingToc39181523260012}} translate a single character ====
==== translate a single character ====


for instance a space into a <tt>“ : ”</tt> character, as follows.
for instance a space into a <tt>“ : ”</tt> character, as follows.


<div style="margin-left:0cm;margin-right:0cm;">'''$ echo "Tecmint.com =>Linux-HowTos,Guides,Tutorials" | tr " " ":"
'''$ echo "Tecmint.com =>Linux-HowTos,Guides,Tutorials" | tr " " ":"
  Tecmint.com:=>Linux-HowTos,Guides,Tutorials'''</div>
  Tecmint.com:=>Linux-HowTos,Guides,Tutorials'''


There are several sequence characters you can use with '''tr''', for more information, see the '''tr''' man page.
There are several sequence characters you can use with '''tr''', for more information, see the '''tr''' man page.


<div style="margin-left:0cm;margin-right:0cm;">$ man tr</div>
$ man tr


That’s all! '''tr''' is a useful command for manipulating text on the command line. In this guide, we showed some useful '''tr command''' usage examples for Linux newbies. You can share your thoughts with us via the comment form below.
That’s all! '''tr''' is a useful command for manipulating text on the command line. In this guide, we showed some useful '''tr command''' usage examples for Linux newbies. You can share your thoughts with us via the comment form below.


== {{anchor|RefHeadingToc7211523260012}} TR Examples ==
== TR Examples ==


tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT.
tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT.
Zeile 996: Zeile 996:
tr stands for translate.
tr stands for translate.


=== {{anchor|RefHeadingToc7231523260012}} Syntax ===
=== Syntax ===


The syntax of tr command is:
The syntax of tr command is:


<div style="margin-left:0cm;margin-right:0cm;">$ tr [OPTION] SET1 [SET2]</div>
$ tr [OPTION] SET1 [SET2]


=== {{anchor|RefHeadingToc7251523260012}} Translation ===
=== Translation ===


If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.
If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.


=== {{anchor|RefHeadingToc7271523260012}} Convert lower case to upper case ===
=== Convert lower case to upper case ===


The following tr command is used to convert the lower case to upper case
The following tr command is used to convert the lower case to upper case


<div style="margin-left:0cm;margin-right:0cm;">$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
  thegeekstuff
  thegeekstuff
  THEGEEKSTUFF</div>
  THEGEEKSTUFF


The following command will also convert lower case to upper case
The following command will also convert lower case to upper case


<div style="margin-left:0cm;margin-right:0cm;">$ tr [:lower:] [:upper:]
$ tr [:lower:] [:upper:]
  thegeekstuff
  thegeekstuff
  THEGEEKSTUFF</div>
  THEGEEKSTUFF


You can also use ranges in tr. The following command uses ranges to convert lower to upper case.
You can also use ranges in tr. The following command uses ranges to convert lower to upper case.


<div style="margin-left:0cm;margin-right:0cm;">$ tr a-z A-Z
$ tr a-z A-Z
   
   
  thegeekstuff
  thegeekstuff
  THEGEEKSTUFF</div>
  THEGEEKSTUFF


=== {{anchor|RefHeadingToc7291523260012}} Translate braces into parenthesis ===
=== Translate braces into parenthesis ===


You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.
You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.


<div style="margin-left:0cm;margin-right:0cm;">$ tr '{}' '()' < inputfile > outputfile</div>
$ tr '{}' '()' < inputfile > outputfile


The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.
The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.


=== {{anchor|RefHeadingToc7311523260012}} Translate white-space to tabs ===
=== Translate white-space to tabs ===


The following command will translate all the white-space to tabs
The following command will translate all the white-space to tabs


<div style="margin-left:0cm;margin-right:0cm;">$ echo "This is for testing" | tr [:space:] '\t'
$ echo "This is for testing" | tr [:space:] '\t'
  This    is      for    testing</div>
  This    is      for    testing


=== {{anchor|RefHeadingToc7331523260012}} Squeeze repetition of characters using -s ===
=== Squeeze repetition of characters using -s ===


In Example 3, we see how to translate space with tabs. But if there are two are more spaces present continuously, then the previous command will translate each spaces to a tab as follows.
In Example 3, we see how to translate space with tabs. But if there are two are more spaces present continuously, then the previous command will translate each spaces to a tab as follows.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "This  is  for testing" | tr [:space:] '\t'
$ echo "This  is  for testing" | tr [:space:] '\t'
  This                    is                      for    testing</div>
  This                    is                      for    testing


We can use -s option to squeeze the repetition of characters.
We can use -s option to squeeze the repetition of characters.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "This  is  for testing" | tr -s [:space:] '\t'
$ echo "This  is  for testing" | tr -s [:space:] '\t'
  This    is      for    testing</div>
  This    is      for    testing


Similarly you can convert multiple continuous spaces with a single space  
Similarly you can convert multiple continuous spaces with a single space  


<div style="margin-left:0cm;margin-right:0cm;">$ echo "This  is  for testing" | tr -s [:space:] ' '
$ echo "This  is  for testing" | tr -s [:space:] ' '
  This is for testing</div>
  This is for testing


==== {{anchor|RefHeadingToc7351523260012}} Delete specified characters using -d option ====
==== Delete specified characters using -d option ====


tr can also be used to remove particular characters using -d option.
tr can also be used to remove particular characters using -d option.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "the geek stuff" | tr -d 't'
$ echo "the geek stuff" | tr -d 't'
  he geek suff</div>
  he geek suff


To remove all the digits from the string, use
To remove all the digits from the string, use


<div style="margin-left:0cm;margin-right:0cm;">$ echo "my username is 432234" | tr -d [:digit:]
$ echo "my username is 432234" | tr -d [:digit:]
  my username is</div>
  my username is


Also, if you like to delete lines from file, you can use [https://www.thegeekstuff.com/2009/09/unix-sed-tutorial-delete-file-lines-using-address-and-patterns/ sed d command].
Also, if you like to delete lines from file, you can use [https://www.thegeekstuff.com/2009/09/unix-sed-tutorial-delete-file-lines-using-address-and-patterns/ sed d command].


=== {{anchor|RefHeadingToc7371523260012}} Complement the sets using -c option ===
=== Complement the sets using -c option ===


You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.
You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.


<div style="margin-left:0cm;margin-right:0cm;">$ echo "my username is 432234" | tr -cd [:digit:]
$ echo "my username is 432234" | tr -cd [:digit:]
  432234</div>
  432234


=== {{anchor|RefHeadingToc7391523260012}} Remove all non-printable character ===
=== Remove all non-printable character ===


The following command can be used to remove all non-printable characters from a file.
The following command can be used to remove all non-printable characters from a file.


<div style="margin-left:0cm;margin-right:0cm;">$ tr -cd [:print:] < file.txt</div>
$ tr -cd [:print:] < file.txt


=== {{anchor|RefHeadingToc7411523260012}} Join lines to one ===
=== Join lines to one ===


The below command will translate all newlines into spaces and make the result as a single line.
The below command will translate all newlines into spaces and make the result as a single line.


<div style="margin-left:0cm;margin-right:0cm;">$ tr -s '\n' ' ' < file.txt</div>
$ tr -s '\n' ' ' < file.txt


== {{anchor|RefHeadingToc35251523260012}} Siehe auch ==
== Siehe auch ==


* [https://de.wikipedia.org/wiki/Sed_(Unix) Sed (Unix)]https://de.wikipedia.org/wiki/Sed_(Unix)
* [https://de.wikipedia.org/wiki/Sed_(Unix) Sed (Unix)]https://de.wikipedia.org/wiki/Sed_(Unix)

Version vom 29. Januar 2022, 10:59 Uhr

Version 76, 2019-05-30

Linux- tr

Linux- tr

Der Befehl tr (von translate = umwandeln oder transliterate = transliterieren) dient dazu, in Texten systematisch Zeichen durch andere Zeichen zu ersetzen. So ist es beispielweise möglich, alle Großbuchstaben einer Datei durch Kleinbuchstaben zu ersetzen oder mehrere aufeinander folgende Leerzeichen durch ein einziges zu ersetzen. Für komplexere Ersetzungen, z.B. für ganze Wörter, empfiehlt sich das wesentlich mächtigere sed.

Aufruf

Die allgemeine Syntax lautet [1]:

tr OPTION ZEICHENFOLGE1 ZEICHENFOLGE2

tr kennt folgende Optionen:


Optionen von tr
Option Beschreibung
-c, -C oder --complement Komplement der angegebenen Zeichenfolge
-d oder --delete Löschen (nicht Ersetzen) von Zeichen
-s oder --squeeze-repeats Mehrere identische aufeinanderfolgende Zeichen durch ein einzelnes ersetzen
-t oder --truncate-set1 Beschneide zunächst den ersten Datensatz auf die Länge des zweiten Datensatzes

Weitere Optionen sind der Manpage zu entnehmen.

Von tr werden folgende Angaben als Befehle interpretiert:


Von tr interpretierte Befehlssequenzen
Option Beschreibung
\\ Backslash
\b Rücktaste
\n Zeilenumbruch
\t Horizontaler Tab
ZEICHEN1-ZEICHEN 2 Alle Zeichen von ZEICHEN 1 bis ZEICHEN2
[:alpha:] Alle Buchstaben
[:blank:] Alle horizontalen Leerzeichen
[:digit:] Alle Zahlen
[:lower:] Alle Kleinbuchstuben
[:upper:] Alle Großbuchstaben

Weitere Angaben sind der Manpage zu entnehmen. Man beachte, dass die Zsh die eckigen Klammern z.B. in [:blank:] als Wildcard-Parameter interpretiert und sie daher nicht an tr weitergibt. Benutzer der Zsh sollten solche Argument daher in einfache oder doppelte Anführungszeichen einschließen.

Beispiele

Ein einfaches Beispiel ist das Ersetzen eines Buchstabens durch einen anderen:

echo Maus | tr M H

Haus

Mit folgendem Befehl werden Groß- in Kleinbuchstaben umgewandelt:

echo 'FLÜSTERN' | tr A-ZÄÖÜ a-zäöü

oder auch

echo 'FLÜSTERN' | tr [:upper:]ÄÖÜ [:lower:]äöü

ergibt

flüstern

… und umgekehrt:

echo 'schreien' | tr a-zäöü A-ZÄÖÜ

SCHREIEN

Bestimmte Zeichen, hier alle Zahlen in der Datei datei.txt, lassen sich mit der Option -d löschen:

tr -d '0-9' < datei.txt

Soll aus mehrere aufeinanderfolgenden Leerzeichen ein einzelnes gemacht werden, kann man die Option -s verwenden:

echo 'd b' |tr -s ' '

d b

Um alle Zeichen zu entfernen, die nicht einer bestimmten Zeichengruppe angehören, kann die Option -c benutzt werden. Im folgenden Beispiel werden alle Zeichen entfernt, die keine Buchstaben sind:

echo 'Die drei ??? treffen die 12 Geschworenen!' | tr -cd '[:alpha:]' > datei

cat datei 
DiedreitreffendieGeschworenen

Mit Hilfe von tr lässt sich ein Text auch sehr leicht Rot13 chiffrieren und dechiffieren:

echo 'Morgen bringen wir Cäsar um' | tr [a-zA-Z] [n-za-mN-ZA-M]

Zbetra oevatra jve Päfne hz

Und wieder zurück:

echo 'Zbetra oevatra jve Päfne hz' | tr [a-zA-Z] [n-za-mN-ZA-M]

Morgen bringen wir Cäsar um

Um in einer Datei Zeichen zu ändern und das Ergebnis in eine zweite Datei zu schreiben, können Umleitungen eingesetzt werden. Mit dem folgenden Befehl werden alle Vorkommen des Buchstabens a in datei1 in den Buchstaben b umgewandelt und das Ergebnis in datei2 geschrieben:

tr a b < datei1 > datei2

Der folgende Befehl entfernt alle Wagenrückläufe („Carriage Return“, mehr unter Zeichensatz-Konverter) und konvertiert so eine Datei datei1 vom Windows- in das Unixformat:

tr -d '\r' < datei1 > ausgabedatei

Alle mehrfach aufeinander folgenden Zeilenumbrüche („new line“) in datei1 werden in jeweils einen umgewandelt:

tr -s '\n' < datei1 > ausgabedatei

Der folgende Befehl führt dazu, dass alle kommaseparierten Elemente einer CSV-Datei datei.csv jeweils in einer neuen Zeile erscheinen:

tr ',' '\n' < datei.csv

tr

tr ist ein Unix-Kommando, dessen Name eine Abkürzung für translate (deutsch: übersetzen) ist, das bestimmte Zeichen aus einem Datenstrom ersetzt oder entfernt.

Das Werkzeug liest den Datenstrom der Standardeingabe, schreibt auf die Standardausgabe und benötigt je nach Modus ein (Löschen und Komprimieren) oder zwei (Ersetzen) Argumente.

Sollen Zeichen ersetzt werden, werden zwei Argumente benötigt, zuerst die zu ersetzenden Zeichen, im zweiten die neuen.

Beispiel:

$ echo Meyer | tr y i

Meier

Es sind mehrfache Ersetzungen einzelner Zeichen auf einmal möglich. Z.B. ersetzt

tr 'abcd' 'jkmn'

alle vorkommenden a durch j, b durch k usw.

Im Alphabet aufeinanderfolgende Zeichen lassen sich dabei mit einem Bindestrich angeben:

tr 'a-d' 'jkmn'

Mit dem Operator s werden alle hintereinander folgenden identischen Zeichen durch ein einzelnes ersetzt. Beispiel:

echo muuuuh | tr -s u muh

Der Operand d löscht alle im ersten Argument angegebenen Zeichen

tr -d '\r'

wobei \r für ein Carriage Return (Bytewert 13) steht. Mit diesem Befehl wird dieses unter Unix nicht verwendete Umbruchzeichen ersatzlos entfernt.

Ist ein c angegeben, so gilt die Umkehrung, also hier

tr -cd '[:alnum:]'

wobei der Ausdruck [:alnum:] für alle alphanumerischen Zeichen steht. Somit werden alle nicht alphanumerischen Zeichen entfernt.

tr für Anfänger

Abhängig von der Art der Arbeit, die Sie auf der Kommandozeile unter Linux erledigen, können Sie ein Dienstprogramm wünschen, das als Schweizer Taschenmesser für die schnelle Textbearbeitung fungieren kann. Gerne gibt es ein Tool namens tr, das sich für diese Rolle qualifiziert. In diesem Tutorial werden wir die Grundlagen von tr anhand einiger leicht verständlicher Beispiele diskutieren.

Aber bevor wir das tun, ist es erwähnenswert, dass alle Beispiele in diesem Artikel auf einem Ubuntu 18.04 LTS-Rechner getestet wurden.

So erklärt es die Man Page des Tools:

Translate, squeeze, and/or delete characters from standard input, writing to standard output.

Und folgendes ist seine Syntax:

tr [OPTION]... SET1 [SET2]

hier ist, was SET bedeutet:

SETs are specified as strings of characters.  Most represent themselves.  Interpreted sequences are: \NNN   character with octal value NNN (1 to 3 octal digits)

\\     backslash
\a     audible BEL
\b     backspace
\f     form feed
\n     new line
\r     return
\t     horizontal tab
\v     vertical tab

Klein- in Großbuchstaben

Angenommen, du möchtest den Satz „linux tutorial on howtoforge“ in Großbuchstaben konvertieren, dann ist hier, wie du dies mit tr tun kannst.

echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"

Der obige Befehl erzeugte die folgende Ausgabe auf meinem System:

LINUX TUTORIAL ON HOWTOFORGE

Zusätzliche Räume abstreifen

Angenommen, Sie haben eine Zeile wie: „HowtoForge ist eine extrem gute Ressource für Linux-Tutorials“. Und die Anforderung ist, zusätzliche Räume von dieser Linie zu entfernen.

Hier ist, wie du tr verwenden kannst, um dies zu tun:

echo 'HowtoForge       is an extremely        good resource for      Linux tutorials' | tr -s '[:space:]'

Hier ist die Ausgabe:

HowtoForge is an extremely good resource for Linux tutorials

Text löschen

Angenommen, Sie möchten die Bindestriche aus der folgenden Zeile löschen: „HowtoForge — ist — ein — extrem — gut — Ressource — für — Linux — Tutorials.“ Dann ist hier, wie Sie dies mit tr tun können.

echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'

Es folgt der Output, den es produziert:

HowtoForge  is  an  extremely  good  resource  for  Linux  tutorials

Zeichen ersetzen

Im vorherigen Abschnitt nehmen wir an, dass die Anforderung darin bestand, Bindestriche durch, sagen wir, Punkte zu ersetzen. Dann ist hier, wie du das mit tr machen kannst.

echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'

Es folgt der Output, den es produziert hat:

HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials

tr

tr is a very useful UNIX command. It is used to transform string or delete characters from the string. Various type of transformation can be done by using this command, such as searching and replacing text, transforming string from uppercase to lowercase or vice versa, removing repeated characters from the string etc. The command can be used for some complicated transformation also. The different uses of tr command are shown in this tutorial.

Syntax:

tr [option] stringValue1 [stringValue2]

option and stringValue2 are optional for tr command. You can use -c, -s and -d option with tr command to do different types of tasks.

Change case

You can change the case of the string very easily by using tr command. To define uppercase, you can use [:upper:] or [A-Z] and to define lowercase you can define [:lower:] or [a-z].

tr command can be used in the following way to convert any string from uppercase to lowercase.

tr [:upper:] [:lower:]

You can use tr command in the following way also to convert any string from lowercase to uppercase.

tr a-z A-Z

Run the following command to convert every small letter of the string,’linuxhint’ into the capital letter.

$ echo linuxhint | tr [:lower:] [:upper:]

You can apply tr command for converting the content of any text file from upper to lower or lower to upper. Suppose, you have text file named, items.txt with the following contents.# Monitor

  1. Keyboard
  2. Mouse
  3. Scanner
  4. HDD


Run the following commands from the terminal to display the content of items.txt and the output of tr command after converting the content of that file from lower to upper case. The following tr command will not modify the original content of the file.

$ cat items.txt
$ tr a-z A-Z < items.txt

You can run the following command to store the output of the tr command into another file named ‘output.txt’.

$ tr [:upper:] [:lower:] < items.txt > output.txt
$ cat output.txt

Translate character

tr command can be used to search and replace any particular character from any text. The following command is used to convert each space of the text, “Welcome to Linuxhint” by newline (\n).

$ echo "Welcome To Linuxhint" | tr [:space:] '\n'

–c option

tr command can be used with -c option to replace those characters with the second character that don’t match with the first character value. In the following example, tr command is used to search those characters in the string ‘bash’ that don’t match with the character ‘b’ and replace them by ‘a’. The output is ‘baaaa’. Four characters are converted here. These are ,’a’,’s’,’h’ and ‘\n’.

$ echo "bash" | tr -c 'b' 'a'

–s option

tr command uses –s option for search and replace any string from a text. In the following example, space (‘ ‘) is replaced by tab (‘\t’).

$ echo "BASH Programming" | tr -s ' ' '\t'

You can use both -c and -s options together with tr command. In the following example, the range of small letter is used as the first string value. For –c option, tr command will search and replace each capital letter by newline (‘\n’) of the file, items.txt and store the output of the command in the file, output.txt.

$ cat items.txt
$ tr -cs [a-z] "\n" < items.txt > output.txt
$ cat output.txt

–d option

-d option used with tr command to search and delete any character or string from a text.  In the following example, tr command will search ‘P’, ‘y’ and ‘t’ in the string “Python is a Programming language” and delete those characters.

$ echo "Python is a Programming language" | tr -d 'Pyt'

-c option can be used with –d option in the tr command to complement the search like precious –cs command. In the following example, tr command with –cd will search all non-digit characters from the string, “Phone No: 985634854” and delete them.

$ echo "Phone No: 985634854" | tr -cd '0-9'

In a similar way, you can run use -cd option in tr command like the following command to remove the non-printable characters from a file. No nonprintable character exists in items.txt. So the output will be the same as the file content.

$ tr -cd "[:print:]" < items.txt

Conclusion

The basic uses of tr command are explained here by using various examples. Hope, this tutorial will help you to learn the purposes of using this command.

Linux tr command

Depending on the kind of work you do on the command line in Linux, you may want a utility that can act as a Swiss army knife of quick text editing. Gladly, there exists a tool dubbed tr, which qualifies for this role. In this tutorial, we will discuss the basics of tr using some easy to understand examples.

Here's how the tool's man page explains it:

Translate, squeeze, and/or delete characters from standard input, writing to standard output.

And following is its syntax:

tr [OPTION]... SET1 [SET2]

here's what SET means:

SETs are specified as strings of characters.  Most represent themselves.  Interpreted sequences are:

       \NNN   character with octal value NNN (1 to 3 octal digits)

       \\     backslash
       \a     audible BEL
       \b     backspace
       \f     form feed
       \n     new line
       \r     return
       \t     horizontal tab
       \v     vertical tab

lower case to upper case

Suppose you want to convert the sentence "linux tutorial on howtoforge" to uppercase, then here's how you can do this using tr.

echo 'linux tutorial on howtoforge' | tr "[:lower:]" "[:upper:]"

The above command produced the following output on my system:

LINUX TUTORIAL ON HOWTOFORGE

Strip extra spaces

Suppose you have a line like: "HowtoForge       is an extremely        good resource for      Linux tutorials". And the requirement is to strip extra spaces from this line.

Here's how you can use tr to do this:

echo 'HowtoForge       is an extremely        good resource for      Linux tutorials' | tr -s '[:space:]'

Here's the output:

HowtoForge is an extremely good resource for Linux tutorials

Delete text

Suppose you want to delete the hyphens from the following line: "HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials." Then here's how you can do this using tr.

echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr -d '-'

Following is the output it produces:

HowtoForge  is  an  extremely  good  resource  for  Linux  tutorials

Replace characters

In the previous section, suppose the requirement was to replace hyphens with, let's say, dots. Then here's how you can do that using tr.

echo 'HowtoForge -- is -- an -- extremely -- good -- resource -- for -- Linux -- tutorials' | tr '-' '.'

Following is the output it produced:

HowtoForge .. is .. an .. extremely .. good .. resource .. for .. Linux .. tutorials

tr examples

Along with the Linux sed command, the tr command stands for translate is used to provide a level of swapping or translation, suppression or deletion of files. The tr command just translates one character to another character. In this article, we’ll share a couple of examples demonstrating some exciting things that we can do with the tr command.

Basic syntax

tr [OPTION] [SET1] [SET2]

SET1 denotes what we wish to translate in the input file, and SET2 means what we want to convert SET1 as the output of the translation. So the sets can be a single character or multiple characters.

Example1: Suppose you just want to replace a in “sahil suri” with b we can use tr sets. We use echo command to send “sahil suri” to tr command. The tr command by default is not able to read data stream. We use Linux inbuilt redirection operators to feed data to tr command.

echo "sahil suri" | tr 'a' 'b'

sbhil suri

Example2: Suppose if you want to replace multiple characters one after the other then we can use below-set examples. Suppose you want to replace a with b, r with x and i with z, below is the case you are looking at.

echo "sahil suri" | tr 'ari' 'bxz'

sbhzl suxz

Note: Make sure that first set and second set have the same number of characters. For example,  i is just replaced with z as we don’t have the third character on the list below.

echo "sahil suri" | tr 'ari' 'bz'

sbhzl suzz

Similarly, we can use sets to convert multiple letters. Some of the sets tr supports are as below.

POSIX Character set

[:digit:] Only the digits 0 to 9

[:alnum:] Any alphanumeric character
[:alpha:] Any alpha character A to Z or a to z.
[:blank:] Space and TAB characters only.
[:xdigit:] Hexadecimal notation 0-9, A-F, a-f.
[:punct:] Punctuation symbols . , ” ‘ ? ! ; : # $ % & ( ) * + – / < > = @ [ ] \ ^ _ { } | ~
[:print:] Any printable character.
[:space:] Any whitespace characters (space, tab, NL, FF, VT, CR). Many system abbreviates as \s.
[:graph:] Exclude whitespace (SPACE, TAB). Many system abbreviate as \W.
[:upper:] Any alpha character A to Z.
[:lower:] Any alpha character a to z.
[:cntrl:] Control Characters NL CR LF TAB VT FF NUL SOH STX EXT EOT ENQ ACK SO SI DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC IS1 IS2 IS3 IS4 DEL.

Character sets

  1. a-z To represent complete lower case alphabets
  2. A-Z to represent upper case alphabets
  3. 0-9 To describe the set of numbers.


lower to upper case.

echo "sahil suri" | tr 'a-z' 'A-Z'

SAHIL SURI

The tr command mentioned above implies to translate all alphabets in lowercase denoted by ‘a-z’ into alphabets in upper case denoted by ‘A-Z’

Convert all characters in input from upper to lower case

echo "SAHIL SURI" | tr 'A-Z' 'a-z'

sahil suri

Translate only particular characters from lower to upper case

echo "sahil suri" | tr 'shlr' 'SHLR'

SaHiL SuRi

In the previous two examples, we gave ranges, but we can use distinct characters as well as shown in the above example.

Use multiple ranges

echo "sahil suri" | tr 'a-dr-z' 'A-DR-Z'

SAhil SURi

translate individual characters as well

Translate braces into parenthesis

echo "{ Hello World }" > infile

tr '{}' '()' < infile > outfile 
cat outfile 
( Hello World )

Translate spaces to new lines.

We use infile as our test file. Use cat command to display the content of the file.

cat infile

solaris linux aix 

cat infile | tr " " "\n"

solaris 
linux 
aix 

cat infile | tr "[:space:] " "\n"

 solaris 
linux 
aix

While using translate, you may use ” ” or [:space:] to represent white space. I find the first option easier to type.

Replace white space

cat infile | tr " " ":"

solaris:linux:aix

cat infile | tr " " "|"

solaris|linux|aix

Replace multiple occurrences

... with a single appearance of the character.

In below example, we replaced numerous spaces with separate space.

cat infile

solaris      linux   aix

tr -s " " < infile

solaris linux aix

In the above case, we used the tr command with -s option to indicate a squeeze operation.This replaces multiple occurrences of a character with a single appearance of the same character.

… with a different character

cat infile

solaris linux aix

tr -s " " ";" < infile

solaris;linux;aix

The above tr command squeezes multiple occurrences of white space into one semicolon character.

Delete all occurances of a character.

To delete occurrences of a character we use the -d option with the tr command followed by the character to be removed.

echo "linuxunix" | tr -d 'u'

linxnix

The above command removes all occurrences of the character u from the input string.

Remove all digits from the input.

echo "james bond 007" | tr -d '0-9'

james bond

Remove all alphabets from the input.

echo "james bond 007" | tr -d 'a-zA-Z'

007

Remove characters except the given

We used -d option to delete characters we mentioned from the input. We may use the -c option with the -d option to delete all characters except those that we mention.

echo "solaris linux hp-ux" | tr -cd 'slh'

slslh

The above tr command removed all characters including the new line leaving behind the characters s,l and h which we mentioned to be removed. Using the -c option is also sometimes referred to as complimenting the set.

Remove all non-alphanumeric and space

echo "solaris | linux 007 ; hp-ux :::: aix" | tr -cd "[:alpha:][:space:][:digit:]"

solaris linux 007 hpux aix

This example could prove to be especially useful when dealing with a file having a lot of junk characters.

Translate non-alphanumeric characters

into a single newline character

echo "james bond 007" | tr -cs 'a-zA-Z0-9' '\n'

james
bond
007

Join lines in a file into a single

cat infile

solaris
linux
aix

tr -s '\n' ' ' < infile

solaris linux aix [root@linuxnix ~]#

The above tr command squeezes the new line character into a single space character.This option can be useful when attempting to consolidate scattered text in a file.

This concludes our exploration of the tr command. Please consider reading our articles about sed which is another utility that provides most of the translation features we discussed in the above examples and a lot more.

Linux tr command

On Unix-like operating systems, the tr command automatically translates (substitutes, or maps) one set of characters to another.

This document covers the GNU/Linux version of tr.

The tr utility copies the standard input to the standard output with substitution or deletion of selected characters.

Syntax

tr [-Ccsu] string1 string2

In this form, the characters in the string string1 are translated into the characters in string2 where the first character in string1 is translated into the first character in string2 and so on. If string1 is longer than string2, the last character found in string2 is duplicated until string1 is exhausted.

tr [-Ccu] -d string1

In this form, the characters in string1 are deleted from the input.

tr [-Ccu] -s string1

In this form, the characters in string1 are compressed as described for the -s option (see below).

tr [-Ccu] -ds string1 string2

In the fourth form, the characters in string1 are deleted from the input, and the characters in string2 are compressed as described for the -s option.

Options

-C Complement the set of characters in string1, that is "-C ab" includes every character except for 'a' and 'b'.
-c Same as -C but complement the set of values in string1.
-d Delete characters in string1 from the input.
-s Squeeze multiple occurrences of the characters listed in the last operand (either string1 or string2) in the input into a single instance of the character. This occurs after all deletion and translation is completed.
-u Guarantee that any output is unbuffered.


How Characters Are Specified

When specifying the characters to translate with tr, the following conventions are used to represent sets (or "classes") of characters.

Any character not described by one of the following conventions represents itself.


\octal A backslash followed by 1, 2 or 3 octal digits represents a character with that encoded value. To follow an octal sequence with a digit as a character, pad the octal sequence on the left with zeroes.
\character A backslash followed by certain special characters maps to special values:


\a The "alert" character, which issues a notification or alert to the terminal.
\b Backspace.
\f Form feed.
\n Newline.
\r Carriage return.
\t Tab.
\v Vertical tab.

A backslash followed by any other character maps to that character.

c-c Character range. For non-octal range endpoints represents the range of characters between the range endpoints, inclusive and in ascending order, as defined by the collation sequence. If either or both of the range endpoints are octal sequences, it represents the range of specific coded values between the range endpoints, inclusive.
[:class:] Represents all characters belonging to the defined character class. Class names are:


alnum Alphanumeric characters.
alpha Alphabetic characters.
blank White space characters.
cntrl Control characters.
digit Numeric characters.
graph Graphic characters.
ideogram Ideographic characters.
lower Lowercase alphabetic characters.
phonogram Phonographic characters.
print Printable characters.
punct Punctuation characters.
rune Valid characters.
space Space characters.
special Special characters.
upper Uppercase alphabetic characters.
xdigit Hexadecimal characters.

When "[:lower:]" appears in string1 and "[:upper:]" appears in the same relative position in string2, it represents the characters pairs from the toupper mapping in the LC_CTYPE category of the current locale. When "[:upper:]" appears in string1 and "[:lower:]" appears in the same relative position in string2, it represents the characters pairs from the tolower mapping in the LC_CTYPE category of the current locale.With the exception of case conversion, characters in the classes are in unspecified order.For specific information as to which ASCII characters are included in these classes, see ctype and related manual pages."[=equiv=]" Represents all characters belonging to the same equivalence class as equiv, ordered by their encoded values.

[#*n] Represents n repeated occurrences of the character represented by #. This expression is only valid when it occurs in string2. If n is omitted, or is zero, it is be interpreted as large enough to extend string2 sequence to the length of string1. If n has a leading zero, it is interpreted as an octal value, otherwise, it is interpreted as a decimal value.


Environment

The LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of tr.

Exit Status

tr returns an exit status of 0 if it operated successfully, and a value greater than zero if an error occurred.

Examples

tr -cs "[:alpha:]" "\n" < file1

Create a list of the words in file1, one per line, where a word is taken to be a maximal string of letters.

tr "[:lower:]" "[:upper:]" < file1

Translate the contents of file1 to uppercase.

tr -cd "[:print:]" < file1

Remove all non-printable characters from file1.

tr "[=e=]" "e"

Remove all "diacritical" marks from accented versions of the letter e.

tr examples

The tr command in UNIX is a command line utility for translating or deleting characters. It supports a range of transformations including uppercase to lowercase, squeezing repeating characters, deleting specific characters and basic find and replace. It can be used with UNIX pipes to support more complex translation. tr stands for translate.

Syntax :

$ tr [OPTION] SET1 [SET2]

Options

-c : complements the set of characters in string.i.e., operations apply to characters not in the given set

-d : delete characters in the first set from the output.
-s : replaces repeated characters listed in the set1 with single occurrence
-t : truncates set1

Convert lower case to upper case

To convert from lower case to upper case the predefined sets in tr can be used.

$cat greekfile

Output:

WELCOME TO

GeeksforGeeks
$cat greekfile | tr “[a-z]” “[A-Z]”

Output:

WELCOME TO

GEEKSFORGEEKS

or

$cat geekfile | tr “[:lower:]” “[:upper:]”

Output:

WELCOME TO

GEEKSFORGEEKS

Translate white-space to tabs

The following command will translate all the white-space to tabs

$ echo "Welcome To GeeksforGeeks" | tr [:space:] '\t'

Output:

Welcome To GeeksforGeeks

Translate braces into parenthesis

You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.

$cat greekfile
 {WELCOME TO} 
GeeksforGeeks
$ tr '{}' '()'   newfile.txt
(WELCOME TO) 
GeeksforGeeks

The above command will read each character from “geekfile.txt”, translate if it is a brace, and write the output in “newfile.txt”.

Squeeze repetition

To squeeze repeat occurrences of characters specified in a set use the -s option. This removes repeated instances of a character.OR we can say that,you can convert multiple continuous spaces with a single space

$ echo "Welcome    To    GeeksforGeeks" | tr -s [:space:] ' '
Welcome To GeeksforGeeks

Delete specified characters

To delete specific characters use the -d option.This option deletes characters in the first set specified.

$ echo "Welcome To GeeksforGeeks" | tr -d 'w'
elcome To GeeksforGeeks

Remove all the digits from the string, use

$ echo "my ID is 73535" | tr -d [:digit:]
my ID is

Complement the sets using -c option

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.

$ echo "my ID is 73535" | tr -cd [:digit:]
73535

Or

$ echo “unix” | tr –c “u” “a”
Uaaa

tr Examples

tr (short for translate) is a useful command line utility that translates and/or deletes characters from stdin input, and writes to stdout. It is a useful program for manipulating text on the command line.

The syntax for running tr command is as follows, where characters in SET1 are translated to characters in SET2.

$ tr flags [SET1] [SET2]

1. A simple tr command

Use case is to change all lower case letters in text to upper case and vice versa, as shown below.

$ cat linux.txt
linux is my life
linux has changed my life
linux is best and everthing to me..:)
$ cat domains.txt | tr [:lower:] [:upper:]
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)

Alternatively

you can use the following command to change all lower case letters to upper case in a file as shown.

$ cat linux.txt | tr [a-z] [A-Z]
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)

To save the results

written to stdout in a file for later processing, use the shell’s output redirection feature (>) as shown.

$ cat linux.txt | tr [a-z] [A-Z] >output.txt
$ cat output.txt 
LINUX IS MY LIFE
LINUX HAS CHANGED MY LIFE
LINUX IS BEST AND EVERTHING TO ME..:)

In regards to the redirection

you can send input to tr using the input redirection and redirect the output to a file using the same command, as shown.

$ tr [a-z] [A-Z] < linux.txt >output.txt

Another useful feature

you can use the -d flag to delete characters, for example to remove the spaces in the domain names using the following command.

$ cat domains.txt
www. tecmint. Com
www. fossmint. Com
www. linuxsay. Com
$ cat domains.txt | tr -d  
www.tecmint.com
www.fossmint.com
www.linuxsay.com

If there are repeated characters in a sequence

(for instance double spaces) in the text you are processing, you can use the -s option to squeeze the characters leaving only one occurrence of it.

$ cat domains.txt
www.tecmint.....com
www.fossmint.com
www.linuxsay.com
$ cat domains.txt | tr -s  
www.tecmint.com
www.fossmint.com
www.linuxsay.com

The -c option

tells tr to use the complement in the given of SET. In this example, we want to delete all the letters and only leave the UID.

$ echo "My UID is $UID" | tr -cd "[:digit:]\n"
OR
$ echo "My UID is $UID" | tr -d "a-zA-Z"

Here is an example of breaking a single line

of words (sentence) into multiple lines, where each word appears in a separate line.

$ echo "My UID is $UID"
My UID is 1000
$ echo "My UID is $UID" | tr " "  "\n"
My 
UID 
is 
1000

Related to the previous example

you can also translate multiple lines of words into a single sentence as shown.

$ cat uid.txt
My 
UID 
is 
1000
$ tr "\n" " " < uid.txt
My UID is 1000

translate a single character

for instance a space into a “ : ” character, as follows.

$ echo "Tecmint.com =>Linux-HowTos,Guides,Tutorials" | tr " " ":"
Tecmint.com:=>Linux-HowTos,Guides,Tutorials

There are several sequence characters you can use with tr, for more information, see the tr man page.

$ man tr

That’s all! tr is a useful command for manipulating text on the command line. In this guide, we showed some useful tr command usage examples for Linux newbies. You can share your thoughts with us via the comment form below.

TR Examples

tr is an UNIX utility for translating, or deleting, or squeezing repeated characters. It will read from STDIN and write to STDOUT.

tr stands for translate.

Syntax

The syntax of tr command is:

$ tr [OPTION] SET1 [SET2]

Translation

If both the SET1 and SET2 are specified and ‘-d’ OPTION is not specified, then tr command will replace each characters in SET1 with each character in same position in SET2.

Convert lower case to upper case

The following tr command is used to convert the lower case to upper case

$ tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
thegeekstuff
THEGEEKSTUFF

The following command will also convert lower case to upper case

$ tr [:lower:] [:upper:]
thegeekstuff
THEGEEKSTUFF

You can also use ranges in tr. The following command uses ranges to convert lower to upper case.

$ tr a-z A-Z

thegeekstuff
THEGEEKSTUFF

Translate braces into parenthesis

You can also translate from and to a file. In this example we will translate braces in a file with parenthesis.

$ tr '{}' '()' < inputfile > outputfile

The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.

Translate white-space to tabs

The following command will translate all the white-space to tabs

$ echo "This is for testing" | tr [:space:] '\t'
This    is      for     testing

Squeeze repetition of characters using -s

In Example 3, we see how to translate space with tabs. But if there are two are more spaces present continuously, then the previous command will translate each spaces to a tab as follows.

$ echo "This   is   for testing" | tr [:space:] '\t'
This                    is                      for     testing

We can use -s option to squeeze the repetition of characters.

$ echo "This   is   for testing" | tr -s [:space:] '\t'
This    is      for     testing

Similarly you can convert multiple continuous spaces with a single space

$ echo "This  is  for testing" | tr -s [:space:] ' '
This is for testing

Delete specified characters using -d option

tr can also be used to remove particular characters using -d option.

$ echo "the geek stuff" | tr -d 't'
he geek suff

To remove all the digits from the string, use

$ echo "my username is 432234" | tr -d [:digit:]
my username is

Also, if you like to delete lines from file, you can use sed d command.

Complement the sets using -c option

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.

$ echo "my username is 432234" | tr -cd [:digit:]
432234

Remove all non-printable character

The following command can be used to remove all non-printable characters from a file.

$ tr -cd [:print:] < file.txt

Join lines to one

The below command will translate all newlines into spaces and make the result as a single line.

$ tr -s '\n' ' ' < file.txt

Siehe auch