Bash – Why does AWK not like dots in one of two substitutions

awkbashcentosscripting

I'm trying to use AWK in a bash script to look for a placeholder string in a template file and replace it with the contents of a variable that (can) contain various special characters.

Example:

awk -v SOURCEIP="$SOURCEIP" REVERSEDNS="$REVERSEDNS" '{
   gsub(/^_TMPSOURCEIP_/, SOURCEIP);
   gsub(/^_TMPREVERSEDNS_/, REVERSEDNS);
   print
}' /home/foo/footemplate

When I try this though and debug, I get this error:

+ awk -v SOURCEIP=1.1.1.1 REVERSEDNS=nz32-cm1.foo.blah.example.com '{
   gsub(/^_TMPSOURCEIP_/, SOURCEIP);
   gsub(/^_TMPREVERSEDNS_/, REVERSEDNS);
   print
}' /home/foo/footemplate
awk: REVERSEDNS=nz32-cm1.foo.blah.example.com
awk:                    ^ syntax error

I infer from the arrow that awk doesn't like the dot in the REVERSEDNS variable… but if that were the case, why would it be OK with dots in the IP address?

Best Answer

It's because you're missing a second -v:

awk -v SOURCEIP="$SOURCEIP" -v REVERSEDNS="$REVERSEDNS" '{
   gsub(/^_TMPSOURCEIP_/, SOURCEIP);
   gsub(/^_TMPREVERSEDNS_/, REVERSEDNS);
   print
}' /home/foo/footemplate

-v needs to be present for each variable you assert. The reason that it places the error at the dot is because this is the place at which awk is certain that you have written invalid syntax.

Related Question