Linux tr命令

kuang:~$ 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.

 

1. 不加选项:

    echo "hello world" | tr 'hello' '12345'

  输出:12445 w5r4d    

    解释:此处tr做了替换操作,SET1就是“hello”, SET2就是“12345”

  建立映射关系:h -> 1

                                e -> 2

                                l  -> 3

                                l  -> 4   /* l字母映射了两次,后一次覆盖了前一次 */

                                o -> 5

        所以: 输出为 12445 w5r4d

   

   如果这个时候SET1的长度 > SET2的长度呢?

   比如:echo "hello world" | tr 'hellowd' '12345'

   输出:12445 55r4 

   w和d都映射成5了,清楚了吧....

  

   如果这个时候SET1的长度 < SET2的长度呢?

   比如:echo "hello world" | tr 'he' '12345'

   输出:12llo world 

   SET2长度多出来的部分没用到就是了 

 

2. -t 选项

    比如:echo "hello world" | tr 'hellowd' '12345'

    输出:12445 55r45

    再比如:echo "hello world" | tr -t 'hellowd' '12345'

    输出:12445 w5r4d

    解释: -t first truncate SET1 to length of SET2

        先把SET1长度截成SET2长度,然后建立映射,再替换...

   

3.  -c 选项

   echo "hello world" | tr -c '[o-q]'  '1'

   输出: 1111o 1o111

   解释:  -c 选项是取补集, 全集是ASCII字符(不确定,哈哈哈哈....)

             -c '[o-q]' : 相当于SET1就等于opq三个字母以外的ASCII字符

             然后你懂了吧...

 

4. -d 选项

   echo "hello world" | tr -d 'hel'

   输出: o word

   解释:  -d 就是将SET1中出现的字符都删掉

 

5. -s 选项

   echo "hello world" | tr -s 'hel'

   输出: helo world

   解释:  -s 是将SET1中出现的字符,遇到重复就紧压..

             这个例子就是: 如果有多个h在一起出现, squeeze成一个h...

              如果有多个e在一起出现, squeeze成一个e...

              如果有多个l在一起出现, squeeze成一个l...

 

原文地址:https://www.cnblogs.com/xiaokuang/p/4674410.html