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=" ansible_ssh_host="
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”:


[lab] ansible_ssh_host=

[ldap] ansible_ssh_host=

[mysql] ansible_ssh_host=

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

awk -v INSERT=" ansible_ssh_host=" "/[ldap]/{print ;print INSERT;next}1" hosts

I correctly get



[ldap] ansible_ssh_host=


Thanks all for your help!

Source: shell

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.