Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 15 Sep 2017 14:47:47 +0200
From:      Polytropon <freebsd@edvax.de>
To:        Ernie Luzar <luzar722@gmail.com>
Cc:        "freebsd-questions@freebsd.org" <freebsd-questions@freebsd.org>
Subject:   Re: Help scripting dns lookup using awk
Message-ID:  <20170915144747.5dc31f69.freebsd@edvax.de>
In-Reply-To: <59BB24E4.6060908@gmail.com>
References:  <59BB24E4.6060908@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Thu, 14 Sep 2017 20:55:00 -0400, Ernie Luzar wrote:
>    host_in="$1"
>    host_out="$2"
>    host_error="$3"
>    truncate -s 0 $host_out
>    truncate -s 0 $host_error
> 
>    cat $host_in | awk '
>      { system(host $1)
>       rc_status = system($0)
>       if (rc_status != 0)
>          print $1 > $host_error
>        else
>          print $1 > $host_out
>      }'
> 
> 
> # command line exec command.
>  >hosts2void-dns_lookup.awk /tmp/aw.hosts \
> /root/good.dns /root/bad.dns
> 
> # This is the output.
> sh: medrx.sensis.com.au: not found
> sh: medrx.sensis.com.au: not found

You're not providing the whole command as needed; system($0) will
only try to execute the hostname, not a "host <something>" command.



> awk: illegal field $(), name "host_error"
>   input record number 1, file
>   source line number 5

The $ is a reserved character in awk to indicate the fields; $0 is
the whole record, $1 the first field, and so on.



> I see 2 problems with my awk code.
> 
> 1. The text output of the host command results is going
>     the console screen. In the sh version I kill the output
>     using > /dev/null  How would I to do something like that in awk.

Combine the command string before executing, for example like this:

	cmd = sprintf("/usr/bin/host %s > /dev/null 2>&1", $1)
	rc = system(cmd)

This should suppress all messages, and you can still evaluate the
return code of the external program call.



> 2. I get that doing  print $1 > $host_error  is not allowed.
>     What is the correct way to pass script variables to awk?

Look closely: Your awk script is in ' ... ' (single quotes). According
to standard sh behavior, this means that $<something> is not expanded
(unlike " ... $<something> ..."). If you want to transfer parameters
into an awk script from a sh "enclosure", use awk's -v parameter.
For example:

	... | awk -v host_out=${host_out} -v host_error=${host_error} '
		# your awk code here
	'



> Now I am wondering if there is a simpler way to do dns lookup
> in awk?

Just tidy up your code a little bit, the basic parts are already
there. ;-)



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20170915144747.5dc31f69.freebsd>