问题
I am trying to insert a line after the Pattern using gawk
.
Let's say, file aa
contains
11
22
33
11
22
33
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
But, if I use:
gawk -v nm=222 '/22/ {if (done++ == 0) print;print nm;next}1' aa
The file aa contains:
11
22
222
33
11
222
33
(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.
回答1:
$ awk '1; $1==nm2 && !a++ {print nm1}' nm1=222 nm2=22 file
11
22
222
33
11
22
33
Explanation:
$ 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
}
回答2:
You can use this:
awk '/^22$/ && !f {f=1; print; print "222"; next} 1' aa.txt
I'm checking if a line contains only a 22
and if the flag f
is not set. In that case I set the flag to 1, print the current line and 222
回答3:
Use this code instead:
gawk -v nm=222 '/22/ {if (done++ == 0){print;print nm;next}};1' aa
If the value 22 is in a variable: in awk
you can not use /constantRegex/
,
you need to use ~
:
sel=22
gawk -v nm=222 -v sel="$sel" '($0~sel) {if (done++ == 0){print;print nm;next}};1' aa
来源:https://stackoverflow.com/questions/39744006/bash-insert-a-line-after-a-pattern-using-gawk