Passing variables into AWK

I'm trying to use awk to write new entries to a hosts file if they don't exist. I need to do so depending on the type of system I have. Below is what I have, but it isn't working.

awk -v myip1=$IP1 myip2=$IP2 myhost1=$HOST1 myhost2=$HOST2'   BEGIN { mqhost1=0; mqhost2=0; stap1=0; stap2=0; }

    /mqhost1/   { mqhost1=1; }
     /mqhost2/    { mqhost2=1; }
       /myip1/    { stap1=1;   }
    /myip2/    { stap2=1;   }
                    { print $0; }
        END     { 
                  if (mqhost1 == 0)
                      printf("myip1          mqhost1.test.com       mqhost1      \n");
                  if (mqhost2 == 0)
                                      printf("myip2          mqhost2.test.com       mqhost2      \n");
                  if (stap1 == 0)
                      printf("$IP1          $HOST1.test.com   $HOST1  \n");
                  if (stap2 == 0)
                                      printf("$IP2          $HOST2.test.com   $HOST2  \n");

                  }' /client_root/etc/hosts > /home/me/hosts  

You need -v for each variable..:slight_smile:

awk -v myip1=$IP1 -v myip2=$IP2 -v myhost1=$HOST1 -v myhost2=$HOST2   

and you can try for variable search like...

$0 ~ myip2 { } 

Thanks, that saved some trouble, however, my output is putting out literal text, not the variable value. My output:

myip1 myhost1.test.com myhost1
myip2 myhost2.test.com myhost2
myip1 myhost1.test.com myhost1
myip2 myhost2.test.com host2

Remove double quotes and you don't need printf also.. In double quotes it is considered as a string..:slight_smile:

if ( ) {print myip1, mqhost1".test.com", mqhost1}
1 Like

The print statements failed with the "." and the "/n" so I had to put the "." in quote and put some other quotes in to accomodate spacing and the /n got removed... but it works

Thank you.