linux shell 腳本攻略學習7---tr命令詳解


tr命令詳解

什么是tr命令?tr,translate的簡寫,translate的翻譯:

[trænsˈleit]

vi. 翻譯, 能被譯出

vt. 翻譯, 解釋, 轉化, 轉變為, 調動

在這里用到的意思是轉化,轉變,轉換,在linux下輸入tr --help查看一下提示:

amosli@amosli-pc:~$ tr --help
Usage: tr [OPTION]... SET1 [SET2]
Translate, squeeze, and/or delete characters from standard input,
writing to standard output.

  -c, -C, --complement    use the complement of SET1
  -d, --delete            delete characters in SET1, do not translate
  -s, --squeeze-repeats   replace each input sequence of a repeated character
                            that is listed in SET1 with a single occurrence
                            of that character
  -t, --truncate-set1     first truncate SET1 to length of SET2
      --help     display this help and exit
      --version  output version information and exit

SETs are specified as strings of characters.  Most represent themselves.
Interpreted sequences are:

  \NNN            character with octal value NNN (1 to 3 octal digits)
  \\              backslash
  \a              audible BEL
  \b              backspace
  \f              form feed
  \n              new line
  \r              return
  \t              horizontal tab
  \v              vertical tab
  CHAR1-CHAR2     all characters from CHAR1 to CHAR2 in ascending order
  [CHAR*]         in SET2, copies of CHAR until length of SET1
  [CHAR*REPEAT]   REPEAT copies of CHAR, REPEAT octal if starting with 0
  [:alnum:]       all letters and digits
  [:alpha:]       all letters
  [:blank:]       all horizontal whitespace
  [:cntrl:]       all control characters
  [:digit:]       all digits
  [:graph:]       all printable characters, not including space
  [:lower:]       all lower case letters
  [:print:]       all printable characters, including space
  [:punct:]       all punctuation characters
  [:space:]       all horizontal or vertical whitespace
  [:upper:]       all upper case letters
  [:xdigit:]      all hexadecimal digits
  [=CHAR=]        all characters which are equivalent to CHAR

Translation occurs if -d is not given and both SET1 and SET2 appear.
-t may be used only when translating.  SET2 is extended to length of
SET1 by repeating its last character as necessary.  Excess characters
of SET2 are ignored.  Only [:lower:] and [:upper:] are guaranteed to
expand in ascending order; used in SET2 while translating, they may
only be used in pairs to specify case conversion.  -s uses SET1 if not
translating nor deleting; else squeezing uses SET2 and occurs after
translation or deletion.

全是英文?翻譯過來看下:

tr [選項]… 集合1 [集合2]

選項說明:

-c, -C, –complement 用集合1中的字符串替換,要求字符集為ASCII。

-d, –delete 刪除集合1中的字符而不是轉換

-s, –squeeze-repeats 刪除所有重復出現字符序列,只保留第一個;即將重復出現字符串壓縮為一個字符串。

-t, –truncate-set1 先刪除第一字符集較第二字符集多出的字符

字符集合的范圍:

\NNN 八進制值的字符 NNN (1 to 3 為八進制值的字符)
\\ 反斜杠
\a Ctrl-G 鈴聲
\b Ctrl-H 退格符
\f Ctrl-L 走行換頁
\n Ctrl-J 新行
\r Ctrl-M 回車
\t Ctrl-I tab鍵
\v Ctrl-X 水平制表符
CHAR1-CHAR2 從CHAR1 到 CHAR2的所有字符按照ASCII字符的順序
[CHAR*] in SET2, copies of CHAR until length of SET1
[CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0
[:alnum:] 所有的字母和數字
[:alpha:] 所有字母
[:blank:] 水平制表符,空白等
[:cntrl:] 所有控制字符
[:digit:] 所有的數字
[:graph:] 所有可打印字符,不包括空格
[:lower:] 所有的小寫字符
[:print:] 所有可打印字符,包括空格
[:punct:] 所有的標點字符
[:space:] 所有的橫向或縱向的空白
[:upper:] 所有大寫字母

 

經過上面的help提示應該大致能夠看明白tr的作用,tr是UNIX命令行家工具箱中的一款精美小工具,它經常用來編寫優美的單行命令。主要用來對來自標准輸入的字符串從set1映射到set2,並將其輸出寫入stdout(標准輸出).set1和set2是字符類或字符集。如果兩個字符集的長度不相等,那么set2會不斷重復其最后一個字符,直到長度與set1相同。如果set2的長度大於set1,那么在set2中超出set1長度的那部分字符則全部被忽略。

其調用格式如上示:

tr [OPTION]... SET1 [SET2]

實際應用1,大小寫轉換:

amosli@amosli-pc:~$ echo "HI_AMOS" | tr "A-Z" 'a-z'
hi_amos

"a-z"和"A-Z"都是集合(set),集合表示方式非常簡單即"起始字符-終止字符"。

實際應用2,加密解密:

amosli@amosli-pc:~$ echo 12345 | tr '0-9' '987654321' #加密
87654
amosli@amosli-pc:~$ echo 87654 | tr '987654321' '0-9' #解密
12345

上面是一個非常有趣的小例子,通過映射來實現簡單的加密解密,看懂這個例子,可以接着往下看古羅馬時期發明的凱撒加密的一種變體ROT13

amosli@amosli-pc:~$ echo "hi,this is amosli" | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
uv,guvf vf nzbfyv
amosli@amosli-pc:~$ echo "uv,guvf vf nzbfyv" | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
hi,this is amosli

ROT13是它自己本身的逆反;也就是說,要還原ROT13,套用加密同樣的算法即可得,故同樣的操作可用再加密與解密。非常神奇!

實際應用3,刪除字符:

ls | tr -d ‘\n’ 刪除換行符(所有內容拼接成一行)
amosli@amosli-pc:~$ echo "hello 132 world 56 " | tr -d '0-9' #刪除數字
hello  world 

實際應用4,字符集補集:

tr -c [set1] [set2]

set1的補集意味着從這個集合中包含set1中沒有的所有字符。

最典型的用法就是從輸入文本中將不在補集中的所有字符全部刪除。例如:

amosli@amosli-pc:~$ echo "hello 123 world " | tr -d -c '0-9 \n'
 123  

在這里,補集中包含了除數字、空格字符和換行符之外的所有字符,因為指定了-d,所以這些字符全部都會被刪除。

實際應用5,用tr壓縮字符:

amosli@amosli-pc:~$ echo "GNU is  not          UNIX . Recursicve right?" | tr -s  ' '
GNU is not UNIX . Recursicve right? 
#tr -s '[set]'

使用-s參數可以壓縮字符串中重復的字符

看另一個例子:

amosli@amosli-pc:~/learn$ cat sum.txt 
5
4
3
5
4
3
amosli@amosli-pc:~/learn$ cat sum.txt | echo $[ $(tr '\n' '+' ) 0 ]
24
amosli@amosli-pc:~/learn$ cat sum.txt | echo $[ $(tr '\n' '+' )  ]
bash: 5+4+3+5+4+3+  : syntax error: operand expected (error token is "+  ")

這里,運用tr實現了加法運算, tr '\n' '+'使用換行符來替換為'+'然后連接起來,最后多出來一個'+'再接上0即實現了加法。

實際應用6,字符類:

tr可以像合作集合一樣使用種不同的字符類,在上面已經列舉過了:

......
[:digit:] 所有的數字
[:graph:] 所有可打印字符,不包括空格
[:lower:] 所有的小寫字符
[:print:] 所有可打印字符,包括空格
[:punct:] 所有的標點字符
[:space:] 所有的橫向或縱向的空白
[:upper:] 所有大寫字母
.......

下面舉例說明:

amosli@amosli-pc:~/learn$ echo amosli | tr '[:lower:]' '[:upper:]'
AMOSLI

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM