微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux系统中tr命令

 

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

@H_404_5@[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

 

@H_404_5@[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

 

扩展:删除空白行

@H_404_5@[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参数删除指定的字符

@H_404_5@[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参数进行字符的替换

@H_404_5@[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:

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

 

扩展:大小写转换

@H_404_5@[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参数  将指定字符外的字符替换为指定字符

@H_404_5@[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 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。