0

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.

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69

3 Answers3

2
$ 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
}
James Brown
  • 36,089
  • 7
  • 43
  • 59
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

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

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