Linux-admin-tr-command

提供:Dev Guides
移動先:案内検索

Linux管理-trコマンド

以下は tr の構文です。 このコマンドは、文字を変換または削除します。

tr [OPTION] SET1 [SET2]

以下は、_tr_で一般的に使用されるスイッチと文字クラスです。

Command Action
-d Delete
-s Squeeze repeated text in SET1 with single occurrence in SET2
[:alnum:] Alpha numeric characters
[:alpha:] All letters
[:digit:] All digits
[:blank:] All horizontal whitespace
[:space:] All horizontal or vertical whitespace
[:graph:] All printable characters, not including spaces
[:print:] All printable characters, including spaces
[:punct:] All punctuation characters
[:lower:] All lowercase characters
[:upper:] All uppercase characters

_tr_は、通常、文字列内の文字を翻訳または削除するために使用されます。 _tr_は、_sed’s_代替コマンドのより単純な代替手段と考えてください。 _stdin_対ファイルからの読み取り。

「use sed」または「use tr」を使用する必要がある場合は、単純な哲学を維持することをお勧めします。 操作が_tr_で単純な場合;これを使って。 ただし、tr_を再帰的に使用することを考え始めたら、_sed’s substitutionコマンドを使用することをお勧めします。

通常、__は、 '- d_ スイッチを使用しない限り、[SET1]を[SET2]の文字に置き換えます。 次に、[SET1]のストリームから文字が削除されます。

names.txtファイルで_tr_を使用して、すべての小文字を大文字に変換します-

[root@centosLocal Documents]# tr [:lower:] [:upper:]  < names.txt
TED:DANIEL:101
JENNY:COLON:608
DANA:MAXWELL:602
MARIAN:LITTLE:903
BOBBIE:CHAPMAN:403
NICOLAS:SINGLETON:203
DALE:BARTON:901
AARON:DENNIS:305
SANTOS:ANDREWS:504
JACQUELINE:NEAL:102
[root@centosLocal Documents]#

「:」文字をタブに戻しましょう-

[root@centosLocal Documents]# tr [:]  [\\t] < names.txt
Ted Daniel  101
Jenny   Colon     608
Dana    Maxwell    602
Marian      Little  903
Bobbie      Chapman 403
Nicolas Singleton   203
Dale    Barton  901
Aaron   Dennis  305
Santos      Andrews    504
Jacqueline  Neal    102
[root@centosLocal Documents]#

結果を保存したい場合はどうしますか? リダイレクトを使用すると非常に簡単です。

[root@centosLocal Documents]# tr [:]  [\\t]  < names.txt >> tabbedNames.txt
[root@centosLocal Documents]# cat tabbedNames.txt
Ted Daniel  101
Jenny   Colon   608
Dana    Maxwell 602
Marian  Little  903
Bobbie  Chapman 403
Nicolas Singleton   203
[root@centosLocal Documents]#

不完全にフォーマットされたテキストに - s またはsqueezeオプションを使用しましょう-

[root@centosLocal Documents]# cat lines.txt
line 1
line     2
line  3
line                      4
line      5
[root@centosLocal Documents]# tr -s [:blank:] ' ' < lines.txt >> linesFormat.txt
[root@centosLocal Documents]# cat linesFormat.txt
line 1
line 2
line 3
line 4
line 5
[root@centosLocal Documents]#