Linux 中 awk指令 sub和substr的区别
001、sub的用法
[root@localhost test]# ls a.txt [root@localhost test]# cat a.txt ## 测试数据 01 02aa 03aa 04 05 06aa 07kk 08 09 10kk 11aa 12 13 14jj 15tt 16 17 18mm 19ee 20 [root@localhost test]# awk '{OFS = "\t"; sub("a", "Q"); print $0}' a.txt ## 将每行的第一个a替换为Q 01 02Qa 03aa 04 05 06Qa 07kk 08 09 10kk 11Qa 12 13 14jj 15tt 16 17 18mm 19ee 20 [root@localhost test]# awk '{OFS = "\t"; sub("a", "Q", $1); print $0}' a.txt ## 限定第一列 01 02aa 03aa 04 05 06aa 07kk 08 09 10kk 11aa 12 13 14jj 15tt 16 17 18mm 19ee 20 [root@localhost test]# awk '{OFS = "\t"; sub("a", "Q", $2); print $0}' a.txt ## 限定第二列 01 02Qa 03aa 04 05 06Qa 07kk 08 09 10kk 11aa 12 13 14jj 15tt 16 17 18mm 19ee 20
002、
[root@localhost test]# ls a.txt [root@localhost test]# cat a.txt ## 测试数据 01 02aa 03aa 04 05 06aa 07kk 08 09 10kk 11aa 12 13 14jj 15tt 16 17 18mm 19ee 20 [root@localhost test]# awk '{a=sub("a", "Q"); print a}' a.txt ## 表达式的值是替换发生的次数 1 1 1 0 0 [root@localhost test]# awk '{a=gsub("a", "Q"); print a}' a.txt ## 表达式的值是替换发生的次数 4 2 2 0 0
。
2、Linux awk语句中substr的用法
[root@localhost test]# cat a.txt ## 测试数据 01 02aa 03aa 04 05 06aa 07kk 08 09 10kk 11aa 12 13 14jj 15tt 16 17 18mm 19ee 20 [root@localhost test]# awk '{a=substr($2, 1, 2); print a}' a.txt ## 提取第二个字段的 从第一个字符开始数,向后数两个字符 02 06 10 14 18 [root@localhost test]# awk '{a=substr($2, 2); print a}' a.txt ## 提取第二个字段的, 从第二个字符开始,一直到最后一个字符 2aa 6aa 0kk 4jj 8mm [root@localhost test]# awk '{a=substr($2,2,2); print a}' a.txt ## 提取第二个字符的, 从第二个字符开始,向后数两个字符 2a 6a 0k 4j 8m [root@localhost test]# awk '{a=substr($2, length($2) - 1); print a}' a.txt ## 提取第二个字段的, 从倒数第二个字符,一直到第二个字段的结尾 aa aa kk jj mm
。
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-10-23 linux 中根据指定列的重复或者唯一输出文本
2023-10-23 linux 中实现根据指定列的重复项输出数据
2021-10-23 R脚本中使用命令行 进行传参
2021-10-23 Bareword "mp4" not allowed while "strict subs" in use at (user-supplied code). ubuntu
2021-10-23 Package libxml-2.0 was not found in the pkg-config search path
2021-10-23 Package libcurl was not found in the pkg-config search path.
2021-10-23 linux系统中目录和普通文件无法使用颜色区分解决方法