ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

linux系统中tr命令

2021-07-05 18:33:55  阅读:306  来源: 互联网

标签:tr cat 命令 centos79 linux test txt root


 

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 "\n"

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

 

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

 

标签:tr,cat,命令,centos79,linux,test,txt,root
来源: https://www.cnblogs.com/liujiaxin2018/p/14973738.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有