Linux命令 tr

  tr命令可以对来自标准输入的内容进行字符转换、字符删除以及重复字符压缩,通常称为转换命令,调用格式如下:

  tr [option] set1 set2,将来自stdin的输入字符从set1映射到set2

1、字符转换

[zhuwan@client01 xargs]$ echo "HELLO WORLD" | tr 'A-Z' 'a-z'
hello world

'a-z'和‘A-Z’都是集合,定义集合,只需要使用“起始字符-终止字符”这种格式就可以了,集合中也可以使用' '和' '等特殊字符

[zhuwan@client01 tr]$ cat file.txt
1 4 7
2 3 5

[zhuwan@client01 tr]$ tr ' ' ' ' < file.txt
1 4 7
2 3 5

2、删除字符

2.1、-d选项,可以指定需要被删除的字符集合

[zhuwan@client01 tr]$ echo "hello 2 4 worl4d" | tr -d '0-9'
hello world

2.2、可以使用-c选项来使用set1的补集,最典型的用法是将不在补集中的字符删除

[zhuwan@client01 tr]$ echo "hello 2 4 worl4d" | tr -d -c '0-9 '
2 4 4

上面这个例子,删除除了“数字、空格、换行符”之外的字符

3、压缩字符

-s选项可以将连续的重复字符压缩成单个字符

[zhuwan@client01 tr]$ echo "This is why i play ?" | tr -s ' '
This is why i play ?

[zhuwan@client01 tr]$ cat file.txt
1 4 7


2 3 5


3435
[zhuwan@client01 tr]$

[zhuwan@client01 tr]$ cat file.txt | tr -s ' '
1 4 7
2 3 5
3435
[zhuwan@client01 tr]$

原文地址:https://www.cnblogs.com/pigwan7/p/8044512.html