tr - translate or delete characters 主要用於轉換和刪除字符
帶有最常用選項的t r命令格式為:
tr -c -d -s [ "string1_to_translate_from" ] [ "string2_to_translate_to" ] input_file
-c 用字符串1中字符集的補集替換此字符集,要求字符集為ASCII。
-d 刪除字符串1中所有輸入字符。
-s 刪除所有重復出現字符序列,只保留第一個;即將重復出現字符串壓縮為一個字符串。
Input-file是轉換文件名。雖然可以使用其他格式輸入,但這種格式最常用。
字符范圍
使用tr時,可以指定字符串列表或范圍作為形成字符串的模式。這看起來很像正則表達式,但實際上不是。指定字符串1或字符串2的內容時,只能使用單字符或字符串范圍或列表。
[a-z] a-z內的字符組成的字符串
[A-Z] A-Z內的字符組成的字符串
[0-9] 數字串
/octal 一個三位的八進制數,對應有效的ASCII字符
[O*n] 表示字符O重復出現指定次數n 如:[O*2]匹配OO的字符串。
大部分tr變種支持字符類和速記控制字符。
字符類格式為[:class],包含數字、希臘字母、空行、小寫、大寫、ctrl鍵、空格、點記符、圖形等等。
去除重復出現的字符 -s 因為都是字母,故使用[a-z]
[python@master2 tr]$ more a.txt helloo worldddd [python@master2 tr]$ cat a.txt |tr -s "[a-z]" helo world [python@master2 tr]$ tr -s "[a-z]" < a.txt helo world
刪除空行
要刪除空行,可將之剔出文件。使用-s來做這項工作。換行的八進制表示為\012
[python@master2 tr]$ more b.txt this is a one line two thress foure [python@master2 tr]$ [python@master2 tr]$ [python@master2 tr]$ tr -s "[\012]"< b.txt this is a one line two thress foure [python@master2 tr]$ tr -s "[\n]" < b.txt this is a one line two thress foure
大寫到小寫
除了刪除控制字符,轉換大小寫是tr最常用的功能。為此需指定即將轉換的小寫字符[a-z]和轉換結果[A-Z]。
第一個例子,tr從一個包含大小寫字母的字符串中接受輸入。
[python@master2 tr]$ echo "May Day,May Day,Going Down.." | tr "[a-z]" "[A-Z]" MAY DAY,MAY DAY,GOING DOWN.. [python@master2 tr]$ [python@master2 tr]$ [python@master2 tr]$ echo "May Day,May Day,Going Down.." | tr "[A-Z]" "[a-z]" may day,may day,going down.. [python@master2 tr]$ echo "Hello World I Love You" |tr [:lower:] [:upper:]
HELLO WORLD I LOVE YOU
刪除指定字符 #-d代表刪除,[0-9]代表所有的數字,[: ]代表冒號和空格
[python@master2 tr]$ more c.txt Monday 09:00 Tuesday 09:10 Wednesday 10:11 Thursday 11:30 Friday 08:00 Saturday 07:40 Sunday 10:00 [python@master2 tr]$ cat c.txt |tr -d "[0-9][:]" Monday Tuesday Wednesday Thursday Friday Saturday Sunday