Tr
Version 76, 2019-05-30
Vorlage:Anchor Linux- tr
Vorlage:Anchor 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.
Vorlage:Anchor Aufruf
Die allgemeine Syntax lautet [1]:
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.
Vorlage:Anchor Beispiele
Ein einfaches Beispiel ist das Ersetzen eines Buchstabens durch einen anderen:
Mit folgendem Befehl werden Groß- in Kleinbuchstaben umgewandelt:
oder auch
ergibt
… und umgekehrt:
Bestimmte Zeichen, hier alle Zahlen in der Datei datei.txt, lassen sich mit der Option -d löschen:
Soll aus mehrere aufeinanderfolgenden Leerzeichen ein einzelnes gemacht werden, kann man die Option -s verwenden:
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:
cat dateiDiedreitreffendieGeschworenen
Mit Hilfe von tr lässt sich ein Text auch sehr leicht Rot13 chiffrieren und dechiffieren:
Und wieder zurück:
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:
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:
Alle mehrfach aufeinander folgenden Zeilenumbrüche („new line“) in datei1 werden in jeweils einen umgewandelt:
Der folgende Befehl führt dazu, dass alle kommaseparierten Elemente einer CSV-Datei datei.csv jeweils in einer neuen Zeile erscheinen:
Vorlage:Anchor 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:
Es sind mehrfache Ersetzungen einzelner Zeichen auf einmal möglich. Z.B. ersetzt
alle vorkommenden a durch j, b durch k usw.
Im Alphabet aufeinanderfolgende Zeichen lassen sich dabei mit einem Bindestrich angeben:
Mit dem Operator s werden alle hintereinander folgenden identischen Zeichen durch ein einzelnes ersetzt. Beispiel:
echo muuuuh | tr -s u
Der Operand d löscht alle im ersten Argument angegebenen Zeichen
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
wobei der Ausdruck [:alnum:] für alle alphanumerischen Zeichen steht. Somit werden alle nicht alphanumerischen Zeichen entfernt.
Vorlage:Anchor 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:
Und folgendes ist seine Syntax:
hier ist, was SET bedeutet:
\\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab\v vertical tab
Vorlage:Anchor 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.
Der obige Befehl erzeugte die folgende Ausgabe auf meinem System:
Vorlage:Anchor 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:
Hier ist die Ausgabe:
Vorlage:Anchor 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.
Es folgt der Output, den es produziert:
Vorlage:Anchor 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.
Es folgt der Output, den es produziert hat:
Vorlage:Anchor 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:
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.
Vorlage:Anchor 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.
You can use tr command in the following way also to convert any string from lowercase to uppercase.
Run the following command to convert every small letter of the string,’linuxhint’ into the capital letter.
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
- Keyboard
- Mouse
- Scanner
- 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.
You can run the following command to store the output of the tr command into another file named ‘output.txt’.
Vorlage:Anchor 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).
Vorlage:Anchor –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’.
Vorlage:Anchor –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’).
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.
$ tr -cs [a-z] "\n" < items.txt > output.txt$ cat output.txt
Vorlage:Anchor –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.
-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.
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.
Vorlage:Anchor 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.
Vorlage:Anchor 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:
And following is its syntax:
here's what SET means:
SETs are specified as strings of characters. Most represent themselves. Interpreted sequences are:
\\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab\v vertical tab
Vorlage:Anchor 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.
The above command produced the following output on my system:
Vorlage:Anchor 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:
Here's the output:
Vorlage:Anchor 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.
Following is the output it produces:
Vorlage:Anchor 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.
Following is the output it produced:
Vorlage:Anchor 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.
Vorlage:Anchor Basic syntax
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.
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.
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.
Similarly, we can use sets to convert multiple letters. Some of the sets tr supports are as below.
Vorlage:Anchor POSIX Character set
[: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.Vorlage:Anchor Character sets
- a-z To represent complete lower case alphabets
- A-Z to represent upper case alphabets
- 0-9 To describe the set of numbers.
Vorlage:Anchor lower to upper case.
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’
Vorlage:Anchor Convert all characters in input from upper to lower case
Vorlage:Anchor Translate only particular characters from lower to upper case
In the previous two examples, we gave ranges, but we can use distinct characters as well as shown in the above example.
Vorlage:Anchor Use multiple ranges
Vorlage:Anchor translate individual characters as well
Translate braces into parenthesis
tr '{}' '()' < infile > outfile
cat outfile
( Hello World )Vorlage:Anchor 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.
Vorlage:Anchor Replace white space
cat infile | tr " " ":"
solaris:linux:aix
cat infile | tr " " "|"
solaris|linux|aix
Vorlage:Anchor 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.
Vorlage:Anchor … 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.
Vorlage:Anchor 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.
The above command removes all occurrences of the character u from the input string.
Vorlage:Anchor Remove all digits from the input.
Vorlage:Anchor Remove all alphabets from the input.
Vorlage:Anchor 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.
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.
Vorlage:Anchor 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.
Vorlage:Anchor Translate non-alphanumeric characters
into a single newline character
james bond007
Vorlage:Anchor 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.
Vorlage:Anchor 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.
Vorlage:Anchor Syntax
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.
In this form, the characters in string1 are deleted from the input.
In this form, the characters in string1 are compressed as described for the -s option (see below).
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.
Vorlage:Anchor 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.
|
Vorlage:Anchor 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 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:
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.
|
Vorlage:Anchor Environment
The LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of tr.
Vorlage:Anchor Exit Status
tr returns an exit status of 0 if it operated successfully, and a value greater than zero if an error occurred.
Vorlage:Anchor Examples
Create a list of the words in file1, one per line, where a word is taken to be a maximal string of letters.
Translate the contents of file1 to uppercase.
Remove all non-printable characters from file1.
Remove all "diacritical" marks from accented versions of the letter e.
Vorlage:Anchor 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 :
Options
-d : delete characters in the first set from the output. -s : replaces repeated characters listed in the set1 with single occurrence-t : truncates set1
Vorlage:Anchor Convert lower case to upper case
To convert from lower case to upper case the predefined sets in tr can be used.
Output:
Output:
or
Output:
Vorlage:Anchor Translate white-space to tabs
The following command will translate all the white-space to tabs
Output:
Vorlage:Anchor 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”.
Vorlage:Anchor 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
Vorlage:Anchor 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
Vorlage:Anchor Remove all the digits from the string, use
Vorlage:Anchor 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.
Or
Vorlage:Anchor 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.
Vorlage:Anchor 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.
linux is my life linux has changed my lifelinux is best and everthing to me..:)
LINUX IS MY LIFE LINUX HAS CHANGED MY LIFELINUX IS BEST AND EVERTHING TO ME..:)
Vorlage:Anchor Alternatively
you can use the following command to change all lower case letters to upper case in a file as shown.
LINUX IS MY LIFE LINUX HAS CHANGED MY LIFELINUX IS BEST AND EVERTHING TO ME..:)
Vorlage:Anchor To save the results
written to stdout in a file for later processing, use the shell’s output redirection feature (>) as shown.
$ cat output.txt LINUX IS MY LIFE LINUX HAS CHANGED MY LIFELINUX IS BEST AND EVERTHING TO ME..:)
Vorlage:Anchor 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.
Vorlage:Anchor 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
Vorlage:Anchor 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
Vorlage:Anchor 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.
OR$ echo "My UID is $UID" | tr -d "a-zA-Z"
Vorlage:Anchor 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
Vorlage:Anchor 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
Vorlage:Anchor translate a single character
for instance a space into a “ : ” character, as follows.
There are several sequence characters you can use with tr, for more information, see the tr man page.
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.
Vorlage:Anchor 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.
Vorlage:Anchor Syntax
The syntax of tr command is:
Vorlage:Anchor 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.
Vorlage:Anchor Convert lower case to upper case
The following tr command is used to convert the lower case to upper case
thegeekstuffTHEGEEKSTUFF
The following command will also convert lower case to upper case
thegeekstuffTHEGEEKSTUFF
You can also use ranges in tr. The following command uses ranges to convert lower to upper case.
thegeekstuffTHEGEEKSTUFF
Vorlage:Anchor 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.
The above command will read each character from “inputfile”, translate if it is a brace, and write the output in “outputfile”.
Vorlage:Anchor Translate white-space to tabs
The following command will translate all the white-space to tabs
Vorlage:Anchor 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.
We can use -s option to squeeze the repetition of characters.
Similarly you can convert multiple continuous spaces with a single space
Vorlage:Anchor Delete specified characters using -d option
tr can also be used to remove particular characters using -d option.
To remove all the digits from the string, use
Also, if you like to delete lines from file, you can use sed d command.
Vorlage:Anchor 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.
Vorlage:Anchor Remove all non-printable character
The following command can be used to remove all non-printable characters from a file.
Vorlage:Anchor Join lines to one
The below command will translate all newlines into spaces and make the result as a single line.
Vorlage:Anchor Siehe auch
- Sed (Unix)https://de.wikipedia.org/wiki/Sed_(Unix)
- tr(1) - Unix achter Handbucheintrag.
- [1] Manpage
- Beispiele aus examplenow.com
- GNU Core Utilities 🇬🇧http://www.gnu.org/software/coreutils/
- tr
- tr: Translate Characters -> Syntax und Beispiele 🇩🇪 – Blogartikel 5/2010
- Shell-Tipps 🇩🇪 – Artikel in EasyLinux 11/2003
- Shell/Befehlsübersicht Übersicht über verschiedene Shell-Befehle