如何在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
相关产品推荐
相关产品推荐

