AWK add line below a search pattern with variable and in a shell script

theres a little problem with using an awk line in a shell script and I can’t find the misstake I made. Hope, anybody can help me.

I use awk version 20070501 and Mac.

I am using the following code to add a line under a specified pattern:

...

ANSHOSTGROUPS=($(egrep "^[.*]$" hosts))
INSERT="dc01.fritz.box ansible_ssh_host=192.168.4.27"
...
awk -v INSERT=$INSERT "/${ANSHOSTGROUPS[2]}/{print ;print INSERT;next}1" hosts > /tmp/tmp_hosts && mv -f /tmp/tmp_hosts hosts

I get the following in the file “hosts”:

[test]
centos7-test.fritz.box

[lab]
dc01.fritz.box ansible_ssh_host=192.168.4.27

[ldap]
dc01.fritz.box ansible_ssh_host=192.168.4.27

[mysql]
dc01.fritz.box ansible_ssh_host=192.168.4.27

Now when I use the following for testing directly on the command line:

awk -v INSERT="dc01.fritz.box ansible_ssh_host=192.168.4.27" "/[ldap]/{print ;print INSERT;next}1" hosts

I correctly get

[test]
centos7-test.fritz.box

[lab]

[ldap]
dc01.fritz.box ansible_ssh_host=192.168.4.27

[mysql]

Thanks all for your help!


Source: shell

Leave a Reply