-2

I create the following awk example script in order to add the line - "line 1" after the line "target"

we set the variable var="target" , to export the value target inside the awk,

But when we run the script , seems that awk not read the value in var

The script with awk:

[root@master tmp]# more test.bash
#!/bin/bash


awk -v var="target" '1; done != 1 && /var/ {
                print "line 1"
                done = 1
                }' file

The file:

[root@master tmp]# more file


target

When I run the script we get:

[root@master tmp]# ./test.bash


target

While expected results should be

target
line 1

I will happy to know what I am wrong with awk syntax,

And how to fix it so var inside the awk will get the value - "target"

King David
  • 500
  • 1
  • 7
  • 20

1 Answers1

0

Instead of /var/ (which looks only for the exact string var, not at the contents of the variable thus named), use the ~ operator:

awk -v var="$target" '
1 { print }
done != 1 && $0 ~ var { print "line 1"; done=1 }
' file
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441