Linux管理員 - tr命令



以下是tr的語法。此命令用於轉換或刪除字元。

tr [OPTION] SET1 [SET2]

以下是tr常用的開關和字元類。

命令 功能
-d 刪除
-s 將SET1中重複的文字在SET2中壓縮為單個出現。
[:alnum:] 字母數字字元
[:alpha:] 所有字母
[:digit:] 所有數字
[:blank:] 所有水平空格
[:space:] 所有水平或垂直空格
[:graph:] 所有可列印字元,不包括空格
[:print:] 所有可列印字元,包括空格
[:punct:] 所有標點符號
[:lower:] 所有小寫字母
[:upper:] 所有大寫字母

tr通常用於轉換或刪除字串中的字元。可以將tr視為sed的替換命令的更簡單的替代方案。從stdin讀取與從檔案讀取。

在考慮應該使用“使用sed”還是“使用tr”時,最好遵循保持簡單的原則。如果tr中的操作很簡單,則使用它。但是,一旦開始考慮遞迴使用tr,最好使用sed的替換命令。

通常,tr會將[SET1]中的字元替換為[SET2]中的字元,除非使用了-d開關。然後,將刪除[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或壓縮選項 −

[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]#
basic_centos_linux_commands.htm
廣告