You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在awk中匹配pattern后直接插入指定字符串?

解决方法

你之前的awk命令固定了字段位置,一旦regex出现在其他字段就失效,用awk的gsub全局替换函数就能完美解决这个问题,不用关心regex在哪个位置:

gsub(/regex/, "regex *new string*") 1 file.txt

或者写成更易懂的形式:

{ gsub(/regex/, "regex *new string*"); print } file.txt

说明:

  • gsub(/regex/, "regex *new string*"):会把当前行里所有匹配regex的内容替换成regex *new string*,不管它在第几字段。
  • 命令里的1是awk的简写,作用是打印处理后的每行,和写print效果一样。

实际测试:

输入file.txt内容:

This is regex in 3rd field
regex in first field
another line with regex

执行命令后输出:

This is regex *new string* in 3rd field
regex *new string* in first field
another line with regex *new string*

刚好符合你的要求。

如果只需要替换每行中第一个出现的regex,把gsub换成sub就行:

sub(/regex/, "regex *new string*") 1 file.txt

内容的提问来源于stack exchange,提问作者Minux-Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:10:29