Linux shell tr 命令詳解
1. 用途
tr,translate的簡寫,主要用于壓縮重復字符,刪除文件中的控制字符以及進行字符轉換操作。
2. 語法
tr [OPTION]... SET1 [SET2]
3. 參數
3.1 -s 壓縮重復字符
-s: squeeze-repeats,用SET1指定的字符來替換對應的重復字符 (replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character)
xiaosi@Qunar:~/test$ echo "aaabbbaacccfddd" | tr -s [abcdf] // abacfd
可以使用這一特點,刪除文件中的空白行,實質上跟上面一樣,都是用SET1指定的字符來替換對應的重復字符
xiaosi@Qunar:~/test$ cat b.txtI like footballFootball is very fun!Helloxiaosi@Qunar:~/test$ cat b.txt | tr -s ["/n"]I like footballFootball is very fun!Hello
3.2 -d 刪除字符
-d:delete,刪除SET1中指定的所有字符,不轉換(delete characters in SET1, do not translate)
xiaosi@Qunar:~/test$ echo "a12HJ13fdaADff" | tr -d "[a-z][A-Z]"1213xiaosi@Qunar:~/test$ echo "a1213fdasf" | tr -d [adfs]1213
3.3 字符替換
-t:truncate,將SET1中字符用SET2對應位置的字符進行替換,一般缺省為-t
xiaosi@Qunar:~/test$ echo "a1213fdasf" | tr -t [afd] [AFO] // A1213FOAsF
上述代碼將a轉換為A,f轉換為F,d轉換為O。
可以利用這一特點,實現大小字母的轉換
xiaosi@Qunar:~/test$ echo "Hello World I Love You" |tr -t [a-z] [A-Z]HELLO WORLD I LOVE YOUxiaosi@Qunar:~/test$ echo "HELLO WORLD I LOVE YOU" |tr -t [A-Z] [a-z]hello world i love you
也可以利用字符集合進行轉換
xiaosi@Qunar:~/test$ echo "Hello World I Love You" |tr -t [:lower:] [:upper:]HELLO WORLD I LOVE YOUxiaosi@Qunar:~/test$ echo "HELLO WORLD I LOVE YOU" |tr -t [:upper:] [:lower:]hello world i love you
備注:
字符集合如下
/NNN 八進制值的字符 NNN (1 to 3 為八進制值的字符)// 反斜杠/a Ctrl-G 鈴聲/b Ctrl-H 退格符/f Ctrl-L 走行換頁/n Ctrl-J 新行/r Ctrl-M 回車/t Ctrl-I tab鍵/v Ctrl-X 水平制表符CHAR1-CHAR2 從CHAR1 到 CHAR2的所有字符按照ASCII字符的順序[CHAR*] in SET2, copies of CHAR until length of SET1[CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0[:alnum:] 所有的字母和數字[:alpha:] 所有字母[:blank:] 水平制表符,空白等[:cntrl:] 所有控制字符[:digit:] 所有的數字[:graph:] 所有可打印字符,不包括空格[:lower:] 所有的小寫字符[:print:] 所有可打印字符,包括空格[:punct:] 所有的標點字符[:space:] 所有的橫向或縱向的空白[:upper:] 所有大寫字母
3.4 字符補集替換
-c:complement,用SET2替換SET1中沒有包含的字符
xiaosi@Qunar:~/test$ cat a.txtMonday 09:00Tuesday 09:10Wednesday 10:11Thursday 11:30Friday 08:00Saturday 07:40Sunday 10:00xiaosi@Qunar:~/test$ cat a.txt | tr -c "[a-z][A-Z]" "#" | tr -s "#" | tr -t "#" "/n"MondayTuesdayWednesdayThursdayFridaySaturdaySunday
上面代碼中 tr -c "[a-z][A-Z]" "#" 表示將除大小字母以外的所有的字符都替換為#。
上面代碼可優化為:
xiaosi@Qunar:~/test$ cat a.txt | tr -cs "[a-z][A-Z]" "/n"MondayTuesdayWednesdayThursdayFridaySaturdaySunday
感謝閱讀,希望嫩幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選