-
TR
(linux命令)
鎖定
TR是linux命令常用命令,其全稱“Text Replacer”,該命令用於進行文本字符替換。
- 中文名
- TR
- 性 質
- 命令
- 特 徵
- 用於進行文本替換
- 全 稱
- Text Replacer
命令簡介
tr用來從標準輸入中通過替換或刪除操作進行字符轉換。 tr主要用於刪除文件中控制字符或進行字符轉換。
特別要注意一點:tr 只能進行字符的替換、縮減和刪除,不能用來替換字符串。
最常用選項的tr命令格式為:
tr -c -d -s ["string1_to_translate_from"] ["string2_to_translate_to"] file
這裏:
-c 用字符串1中字符集的補集替換此字符集,要求字符集為ASCII。
-d 刪除字符串1中所有輸入字符。
-s 刪除所有重複出現字符序列,只保留第一個;即將重複出現字符串壓縮為一個字符串。
file是轉換文件名。雖然可以使用其他格式輸入,但這種格式最常用。
字符範圍
指定字符串1或字符串2的內容時,只能使用單字符或字符串範圍或列表。
[a-z] a-z內的字符組成的字符串。
[A-Z] A-Z內的字符組成的字符串。
[0-9] 數字串。
\octal 一個三位的八進制數,對應有效的ASCII字符。
[O*n] 表示字符O重複出現指定次數n。因此[O*2]匹配OO的字符串。
tr中特定控制字符的不同表達方式
速記符含義八進制方式
\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
應用例子
(1)去除oops.txt裏面的重複的小寫字符 ( # -s會保留第一個字符)
[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)小寫到大寫
[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會全部刪除,但-s會保留第一個)
[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)替代指定的字符(#一對一的替代)
[root@localhost ~]# cat oops.txt ddddfffabccccc errrrdddd [root@localhost ~]# cat oops.txt | tr "bd" "BD" > result.txt [root@localhost ~]# cat result.txt DDDDfffaBccccc errrrDDDD
- 詞條統計
-
- 瀏覽次數:次
- 編輯次數:9次歷史版本
- 最近更新: 君伟junwei521