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

 

posted @   小鲨鱼2018  阅读(1031)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示