tr经常用来编写优美的单行命令。tr可以对来自标准输入的内容进行字符替换、字符删除以及重复字符压缩。
它可以将一组字符变成另一组字符,因而通常被称为转换(translate)命令。
tr只能通过stdin(标准输入),而无法通过命令行参数来接受输入。调用格式如下:
tr [options] set1 set2
将来自stdin的输入字符从set1 映射到set2,然后将输出写入stdout。set1和set2是字符类或字符集。如果set2的长度小于set1,那么set2会不断重复其最后一个字符,知道长度与set1相同。如果set2的长度大于set1,那么在set2中超出set1长度的那部分字符全部忽略。
1. 字符替换:
将输入字符由大写转换成小写,可以使用如下命令:
chicol@debian:~$ echo "HELLO WHO IS THIS" | tr 'A-Z' 'a-z'
hello who is this
用tr进行数字加密和解密:
chicol@debian:~$ echo 12345 | tr '0-9' '9-0'
tr: range-endpoints of `9-0' are in reverse collating sequence order
chicol@debian:~$ echo 12345 | tr '0-9' '9876543210' #加密
87654
chicol@debian:~$ echo 87654 | tr '9876543210' '0-9' #解密
12345
chicol@debian:~$
ROT13加密算法,文本的加密和解密都使用同一个函数:
chicol@debian:~$ echo "Hi, bob! How are you?" | tr 'a-zA-Z' 'n-za-mN-ZA-M'
Uv, obo! Ubj ner lbh?
chicol@debian:~$ echo "Uv, obo! Ubj ner lbh?" | tr 'a-zA-Z' 'n-za-mN-ZA-M'
Hi, bob! How are you?
chicol@debian:~$
tr还可以将制表符转换成空格:
chicol@debian:~/scripts/example$ cat file.txt
abc hello yes jh.
chicol@debian:~/scripts/example$ cat -T file.txt
abc^Ihello yes^Ijh.
chicol@debian:~/scripts/example$ tr '\t' ' ' < file.txt
abc hello yes jh.
chicol@debian:~/scripts/example$
2. tr删除字符
用法:tr -d ‘[set1]’
chicol@debian:~$ echo "Hello 123 world 456" | tr -d '0-9'
Hello world
3. 字符集补集的使用
用法:tr -c [set1] [set2] #set2是可以选的
set1的补集就是这个集合中没有的所有字符。
chicol@debian:~$ echo hello 1 char 2 next 4 | tr -d -c '0-9 \n' #将补集中的全部字符删除
1 2 4
4. 字符压缩
用法:tr -s [set1]
chicol@debian:~$ echo "hello world. It's so beautiful. Isn't it?" | tr -s ' '
hello world. It's so beautiful. Isn't it?
chicol@debian:~$
tr还可以这样用:
1)root@debian:/home/chicol/scripts/chapter_2# cat sum.txt
1
2
3
4
5
root@debian:/home/chicol/scripts/chapter_2# cat sum.txt | echo $[ $( tr '\n' '+' ) 0 ]
15
2)root@debian:/home/chicol/scripts/chapter_2# cat multi_blanks.txt
line1
line2
line3
line4
line5
root@debian:/home/chicol/scripts/chapter_2# cat multi_blanks.txt | tr -s '\n'
line1
line2
line3
line4
line5
字符类:
alnum: 字母和数字
alpha: 字母
lower: 小写字母
upper: 大写字母
digit: 数字
xdigit: 十六进制字符
space: 空白字符
字符类使用方式:
tr [:class:] [:class:]
tr '[:lower:]' '[:upper:]'
阅读(2058) | 评论(0) | 转发(0) |