tr 用來從標準輸入中通過替換或刪除操作進行字元轉換.tr 主要用於刪除檔案中控制字元或進行字元在轉換. 使用 tr 時要轉換兩個字串: 字串 1 用於查詢, 字串 2 用於處理各種轉換.tr 剛執行時, 字串 1 中字元被對映到字串 2 中的字元, 然後轉換操作開始.
語法:
tr  [-cdst] [SET1] [SET2] [>newfile] [newfile : 我們可以將結果匯入新的檔案儲存;
 /root/passwd.linux
這裏的”r” 指的是 dos 的斷行字元
# ll /etc/passwd /root/passwd*
-rw-r–r–. 1 root root 891 Apr  2 06:01 /etc/passwd
-rw-r–r–. 1 root root 911 Apr 17 10:46 /root/passwd
-rw-r–r–. 1 root root 891 Apr 17 10:47 /root/passwd.linux
處理過後, 發現檔案大小與原來的/etc/passwd 就一致了.
 
範例 3: 刪除空白行
刪除空白行就是刪除換行符/n
注意: 這些空白行上只有回車符, 沒有空格符
# cat test.txt
I lovve linux!
 
Hello World!
 
Shell is worthy to been studied!
這裏使用換行符的轉義字元 n
注意: 若用-d, 則會刪除所有的換行符, 如下:
# cat test.txt | tr -d [“n”]
I lovve linux!Hello World!Shell is worthy to been studied!
而此處用-s 刪除多餘的換行符呢, 如下:
[root@sqj2015 ~]# cat test.txt | tr -s [“n”]
I lovve linux!
Hello World!
Shell is worthy to been studied!
 
範例 4: 刪除指定的字元
# cat test.txt
Monday 1:00
Tuessday 2:00
Wednesday 3:00
現在要刪除處理星期之外的所有字元
-d 代表刪除,[0-9] 代表所有的數字,[: ] 代表冒號和空格
# cat test.txt | tr -d “[0-9][: ]”
Monday
Tuessday
Wednesday
 
範例 5: 利用-c 進行補集的替換
有時候在文字中我們只知道要保留一些字元, 其他字元種類繁多, 就可以使用補集的替換
# cat test.txt
Monday 1:00
Tuessday 2:00
Wednesday 3:00
我們只需要星期, 則思路就是除了字母, 其他統統替換掉
這裏,-c 用換行符替換掉除了字元外的所有字元,-s 刪除多餘的換行符
# cat test.txt | tr -cs “[a-z][A-Z]” “n”
Monday
Tuessday
Wednesday