tr用法
?tr用來(lái)從標(biāo)準(zhǔn)輸入中通過(guò)替換或刪除操作進(jìn)行字符轉(zhuǎn)換。 tr主要用于刪除文件中控制字符或進(jìn)行字符轉(zhuǎn)換。
特別要注意一點(diǎn):tr 只能進(jìn)行字符的替換、縮減和刪除,不能用來(lái)替換字符串。
最常用選項(xiàng)的tr命令格式為:?
tr -c -d -s ["string1_to_translate_from"] ["string2_to_translate_to"] file?
這里:?
-c 用字符串1中字符集的補(bǔ)集替換此字符集,要求字符集為ASCII。?
-d 刪除字符串1中所有輸入字符。?
-s 刪除所有重復(fù)出現(xiàn)字符序列,只保留第一個(gè);即將重復(fù)出現(xiàn)字符串壓縮為一個(gè)字符串。?
file是轉(zhuǎn)換文件名。雖然可以使用其他格式輸入,但這種格式最常用。
字符范圍?
指定字符串1或字符串2的內(nèi)容時(shí),只能使用單字符或字符串范圍或列表。?
[a-z] a-z內(nèi)的字符組成的字符串。?
[A-Z] A-Z內(nèi)的字符組成的字符串。?
[0-9] 數(shù)字串。?
\octal 一個(gè)三位的八進(jìn)制數(shù),對(duì)應(yīng)有效的ASCII字符。?
[O*n] 表示字符O重復(fù)出現(xiàn)指定次數(shù)n。因此[O*2]匹配OO的字符串。?
tr中特定控制字符的不同表達(dá)方式?
速記符含義八進(jìn)制方式?
\a Ctrl-G? 鈴聲\007?
\b Ctrl-H? 退格符\010?
\f Ctrl-L? 走行換頁(yè)\014?
\n Ctrl-J? 新行\(zhòng)012?
\r Ctrl-M? 回車\015?
\t Ctrl-I? tab鍵\011?
\v Ctrl-X? \030?
應(yīng)用例子
(1)去除oops.txt里面的重復(fù)的小寫(xiě)字符?(?#? -s會(huì)保留第一個(gè)字符)
?????????[root@localhost ~]# cat oops.txt
???????? ddddfffabccccc
???????? lerrrrdddd
???????? [root@localhost ~]#?tr -s "[a-z]" < oops.txt > result.txt
???????? [root@localhost ~]# cat result.txt
???????? dfabc
???????? lerd
?
(2)刪除空行?
???????[root@localhost ~]# cat oops.txt
?????? ddddfffabccccc
?
?????? lerrrrdddd
?????? [root@localhost ~]#??tr -s "[\012]" < oops.txt > result.txt
?????? [root@localhost ~]# cat result.txt
?????? ddddfffabccccc
?????? lerrrrdddd
(3)刪除所有空行
??????? [root@localhost ~]# cat oops.txt
??????? ddddfffabccccc
?
??????? lerrrrdddd
??????? [root@localhost ~]#?tr -d "[\012]" < oops.txt > result.txt
??????? [root@localhost ~]# cat result.txt
??????? ddddfffabccccclerrrrdddd
(4)小寫(xiě)到大寫(xiě)?
????????[root@localhost ~]# cat oops.txt
??????? ddddfffabccccc
??????? errrrdddd
??????? [root@localhost ~]#?cat oops.txt | tr "[a-z]" "[A-Z]" > result.txt
??????? [root@localhost ~]# cat result.txt
??????? DDDDFFFABCCCCC
??????? ERRRRDDDD
(5)刪除指定的字符(# -d 與 -s 不同,-d會(huì)全部刪除,但-s會(huì)保留第一個(gè))
???????? [root@localhost ~]# cat oops.txt
???????? ddddfffabccccc
???????? errrrdddd
???????? [root@localhost ~]#?cat oops.txt | tr -d "[bd]" > result.txt
???????? [root@localhost ~]# cat result.txt
???????? fffaccccc
???????? errrr
???????? [root@localhost ~]#?cat oops.txt | tr -s "[bd]" > result.txt
???????? [root@localhost ~]# cat result.txt
???????? dfffabccccc
???????? errrrd
(6)替代指定的字符(#一對(duì)一的替代)
?????????[root@localhost ~]# cat oops.txt
???????? ddddfffabccccc
???????? errrrdddd
???????? [root@localhost ~]#?cat oops.txt | tr "[bd]" "[BD]" > result.txt
???????? [root@localhost ~]# cat result.txt
???????? DDDDfffaBccccc
???????? errrrDDDD
轉(zhuǎn)載于:https://blog.51cto.com/6272407/1165236
總結(jié)
- 上一篇: puppet初探
- 下一篇: java中c/s模式传送数据