linux系统中tr命令

1、tr命令 -s 参数将多个连续的字符压缩为一个字符

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
a
a
bbbb
ddddcccc
[root@centos79 test]# tr -s abcd < a.txt    ## 将任一连续的a、b、c、d字符压缩为一个字符
abac
a
a
b
dc
[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -s a Y  ## 将多个连续的a压缩为Y
YbbbYccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -s ab YM  ## 将多个连续的a、连续的b分别压缩为Y和M
YMYccc
M
ddddcccc

扩展:删除空白行

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat -A a.txt
$
$
aaabbbaaaccc$
$
$
bbbb$
$
$
ddddcccc$
[root@centos79 test]# cat a.txt | tr -s "
"

aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -s "
" | sed 1d
aaabbbaaaccc
bbbb
ddddcccc

2、 -d参数删除指定的字符

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -d c
aaabbbaaa
bbbb
dddd
[root@centos79 test]# cat a.txt | tr -d cb
aaaaaa

dddd
[root@centos79 test]# cat a.txt | tr -d cba


dddd

3、-t参数进行字符的替换

[root@centos79 test]# ls
a.txt
[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -t a X
XXXbbbXXXccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -t acd XYM   
XXXbbbXXXYYY
bbbb
MMMMYYYY

可以省略-t:

[root@centos79 test]# cat a.txt | tr  a X   
XXXbbbXXXccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr  acd XYM   ## 连续替换多个字符
XXXbbbXXXYYY
bbbb
MMMMYYYY

扩展:大小写转换

[root@centos79 test]# cat a.txt
aaaccc
BBB
DDDcccc
[root@centos79 test]# cat a.txt | tr -t a-z A-Z
AAACCC
BBB
DDDCCCC
[root@centos79 test]# cat a.txt
aaaccc
BBB
DDDcccc
[root@centos79 test]# cat a.txt | tr -t A-Z a-z
aaaccc
bbb
dddcccc

4、-c参数  将指定字符外的字符替换为指定字符

[root@centos79 test]# cat a.txt
aaabbbaaaccc
bbbb
ddddcccc
[root@centos79 test]# cat a.txt | tr -c a M   ## 将a字符外的字符全部替换为M
aaaMMMaaaMMMMMMMMMMMMMMMMMM[root@centos79 test]# cat a.txt | tr -c a M | sed 's/$/
/'
aaaMMMaaaMMMMMMMMMMMMMMMMMM
[root@centos79 test]# cat a.txt | tr -c ab M | sed 's/$/
/'  ## 将ab外的字符全部替换为M
aaabbbaaaMMMMbbbbMMMMMMMMMM

参考:https://www.cnblogs.com/faberbeta/p/linux-shell003.html 

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14973738.html