linuxshellawksedsystem-administration

Cut awk field value


I have this "answer section" from a dig call:

www.google.com 300 IN A \<ip_address\>

I want to extract the sub-domain www out of the www.google.com to save in a variable.

I have tried to use sed to filter out the sub-domain name, then replace field one (i.e. $1), after passing to awk, with $host_name, like so:

host_name=$(echo get_dig "$@" | sed 's/..*//; s/ .*//')
...
get_dig "$@" | awk '{ $1 = $host_name; printf("The subdomain %s is a %s record and points to %s\\n", $1, $4, $5) }'

N.B: get_dig is a shell function I created to run dig and extract the "answer section".

I have tested and the sed part cuts as I expect it to and gives the correct result (i.e. www), but when I try to replace $1 with $host_name, it seems to alter the behaviour and returns the whole dig "answer section" as the hostname in the printf string. Also, I have $hostname declared globally.

PS: I have to use awk, but it's possible that I might have tunnel-visioned into a particular process, with sed


Solution

  • You never need sed when you're using awk. I think this is what you're trying to do, using any awk:

    echo 'www.google.com 300 IN A \<ip_address\>' |
    awk '{
        sub(/\..*/,"",$1);
        printf "The subdomain %s is a %s record and points to %s\n", $1, $4, $5
    }'
    The subdomain www is a A record and points to \<ip_address\>
    

    Replace the echo '...' with get_dig "$@" (which I obviously don't have).

    As for why your script didn't work, see How do I use shell variables in an awk script? and get rid of the echo in front of get_dig in the pipe to sed.