bash:使用gawk在图案后插入一行 [英] bash: insert a line after a pattern using gawk
本文介绍了bash:使用gawk在图案后插入一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用gawk
在图案后插入一行.
假设文件aa
包含
I am trying to insert a line after the Pattern using gawk
.
Let's say, file aa
contains
11
22
33
11
22
33
我仅在前22个之后(即在插入之后)使用gawk插入222,我的aa文件将包含:
I'm using gawk to insert 222 only after first 22, i.e. after insertion, my aa file would contain:
11
22
222
33
11
22
33
但是,如果我使用:
gawk -v nm=222 '/22/ {if (done++ == 0) print;print nm;next}1' aa
文件aa包含:
11
22
222
33
11
222
33
(我不希望第二次用222替换22,并且希望按原样保留22,并且不再需要插入,也就是说,在第一个22之后仅插入一次222. 请帮忙.
(I don't want second replacement of 22 by 222 and like to retain 22 as-is, and no more insertion, i,e,. insert 222 only once after first 22. Please help.
推荐答案
$ awk '1; $1==nm2 && !a++ {print nm1}' nm1=222 nm2=22 file
11
22
222
33
11
22
33
说明:
$ cat script.awk
1 # print the line
$1==nm2 && !a++ { # if $1 is exactly the desired and a counter hasn't been touched yet
print nm1 # print parameter nm2
}
这篇关于bash:使用gawk在图案后插入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文