tr

Aus Foxwiki


tr - in Texte systematisch Zeichen durch andere Zeichen ersetzen

Beschreibung

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.

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.

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.

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.

So erklärt es die Man Page des Tools:

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

Anwendungen

Einfaches Beispiel

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

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.

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.

  1. Monitor
  2. Keyboard
  3. Mouse
  4. Scanner
  5. 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

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:]' 
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

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.

Fehlerbehebung

Syntax

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

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

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.

tr OPTION ZEICHENFOLGE1 ZEICHENFOLGE2
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.

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.


Optionen

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

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.

Parameter

Umgebungsvariablen

Exit-Status

Siehe auch

Dokumentation

RFC

Man-Pages

Info-Pages

Links

Projekt

Weblinks