可以把tr看作為一個簡化的sed工具,tr表示為:translate。tr命令主要用於實現以下兩個功能
替換操作的字符串轉換。
刪除操作的字符串轉換,可以很容易的刪除一些控制字符或者是空行。
tr命令能夠實現的功能,都能夠用sed命令來實現。但就具體的替換功能來說,tr用起來更容易,也比較簡單。
一,命令格式
[html] view plaincopy
tr [option] ["string1"] ["string2"] < file
常用的選項有:
默認選項。就是沒有任何選項的時候,tr默認為替換操作,就是將string1在文件中出現的字符替換為string2中的字符,這里要注意的是替換關系。
-c選項,用string1中字符的補集替換string1,這里的字符集為ASCII。
-d選項,刪除文件中所有在string1中出現的字符。
-s選項,刪除文件中重復並且在string1中出現的字符,只保留一個。
-c選項在使用時,只是將string1替換為現在的補集,如在使用
[html] view plaincopy
[root@localhost client]# echo "hello world,root,2012" | tr -c "0-9" "*"
*****************2012*
可以看出,我們使用0-9,添加-c選項后,會把0-9替換為其補集,這時補集自然不包含0-9,而包含很多其它的字符,接下來就把所有的其它字符都替換成*號,但不包含數字。
如果只需要替換數字的話:
[html] view plaincopy
[root@localhost client]# echo "hello world,root,2012" | tr "0-9" "*"
hello world,root,****
二,字符串的取值范圍
指定string或string2的內容時,只能使用單字符或字符串范圍或列表。
[a-z] a-z內的字符組成的字符串。
[A-Z] A-Z內的字符組成的字符串。
[0-9] 數字串。
\octal 一個三位的八進制數,對應有效的ASCII字符。
[O*n] 表示字符O重復出現指定次數n。因此[O*2]匹配OO的字符串。
三,控制字符的不同表達方式
速記符 含義 八進制方式
\a Ctrl-G 鈴聲\007
\b Ctrl-H 退格符\010
\f Ctrl-L 走行換頁\014
\n Ctrl-J 新行\012
\r Ctrl-M 回車\015
\t Ctrl-I tab鍵\011
\v Ctrl-X \030 注意這些控制字符,如果想在linux下輸入,如我們可能需要輸入^M這種字符,只需ctrl+V+M同時按下即可。
四,字符替換
這是tr的默認操作,先看下面的命令和輸出
[html] view plaincopy
[root@localhost client]# echo "hello world" | tr "a-z" "A-Z"
HELLO WORLD
[root@localhost client]# echo "hello world" | tr "a-l" "A-Z"
HELLo worLD
[root@localhost client]# echo "hello world" | tr "a-z" "A-H"
HEHHH HHHHD
第一行輸出就是將小寫換成大寫。
第二行輸出將小寫中的a-l分別換成A-L,而將小寫中的l以后的字符都不替換。
第三行輸出將小寫中的a-h換成A-H,而h以后的字符都換成H,因為后者的替換空間沒有前面的字符空間大,所以就重復后面的H,相當於后面的字符是A-HHH......HHHHH。
如果我們想要進行大小寫轉換,可以按下面的輸入:
[html] view plaincopy
tr "a-z" "A-Z" < inputfile
五,去除重復字符
這個時候,所用的選項是-s選項,如:
[html] view plaincopy
[root@localhost client]# echo "hello world,root" | tr -s "ao"
hello world,rot
[root@localhost client]# echo "hello world,root" | tr -s "lo"
helo world,rot
[root@localhost client]# echo "hello world,root" | tr -s "a-z"
helo world,rot
[root@localhost client]# echo "hello world,root" | tr -s "0-9"
hello world,root
第一行表示將輸入字符串中的包含在"ao"字符集中的重復字符去掉,只留一個。因為"hello world,root",只有o滿足條件,所以將root變成rot,把中間的兩個o變成一個。
第二行將hello和root兩個字符都壓縮了。
第三行表示將a-z中的除復字符都去掉。
第三行表示將字符串中的重復的且重復字符在0-9字符集中的字符去掉,這里沒有。
如果我們想要去掉空行,可以這樣操作:
[html] view plaincopy
tr -s "\n" < inputfile 或者 tr -s "\012" <inputfile // 這兩個是一樣的。
就是將重復的換行符去掉,只留一個。
六,刪除字符
-d選項和-s選項類似,只不過-d選項會刪除所有出現的字符。
[html] view plaincopy
[root@localhost client]# echo "hello world,root" | tr -d "a-h"
llo worl,root
[root@localhost client]# echo "hello world,root,2012" | tr -d "a-z"
,,2012
[root@localhost client]# echo "hello world,root,2012" | tr -d "0-9"
hello world,root,