(1) tr 字元替換
測試文字內容 # cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 loalhost localhost.localdomain localhost6 localhost6.localdomain6
把小寫字母替換成大寫字母 # tr "[a-z]" "[A-Z]" < /etc/hosts 127.0.0.1 LOCALHOST LOCALHOST.LOCALDOMAIN LOCALHOST4 LOCALHOST4.LOCALDOMAIN4 ::1 LOALHOST LOCALHOST.LOCALDOMAIN LOCALHOST6 LOCALHOST6.LOCALDOMAIN6
把:替換成空格 # tr ":" " " < /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 1 loalhost localhost.localdomain localhost6 localhost6.localdomain6
注意這種是3-a、4-b、5-c的一一對應替換方式 # echo 112233445566 | tr "345" "abc" 1122aabbcc66
(2) -s 將連續相同的字元壓縮成1個字元
# echo 1122333444555 | tr -s "3" 11223444555 # echo 1122333444555 | tr -s "12345" 12345 去除空行 # cat 1.txt | tr -s "[\n]"
(3) tr -s " " " " 替換且壓縮
# cat 5.txt root tty1 2016-05-22 18:11 (:0) 把空格替換成換行符,並且壓縮了(因為原本中間是有多個空格的) # tr -s " " "\n" <5.txt root tty1 2016-05-22 18:11 (:0) 對比一下不壓縮的情況 # tr " " "\n" <5.txt root tty1 2016-05-22 18:11 (:0)
(4) -d 刪除
# cat 1.txt 123And the cowwwwwssssss went homeeeeeeeee 456i havvvvve 789theyyyyyyyyy 刪除所有字母 # tr -d "A-z" < 1.txt 123 456 789 tr支援刪除 \n\t等字元 # cat 1.txt | tr -d "\n" And the cowwwwwssssss went homeeeeeeeeei havvvvve theyyyyyyyyy[root@sxjy rh7]# 刪除“And”字元 # tr -d [And] < 1.txt 123 the cowwwwwssssss wet homeeeeeeeee 456i havvvvve 789theyyyyyyyyy
刪除轉換控制字元: ^的八進位制程式碼是136,^M是015,tab鍵是011,^Z是032 # cat 1.txt | tr -d '[\011\015]'