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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律