Search code examples
linuxkubernetesawknslookup

nslookup and awk get 2nd address


I'm trying to get the address from the below result of my nslookup

Here I want to get is the 2nd address which is 10.0.45.45

Server:         10.152.183.10
Address:        10.152.183.10#53

Name:   pg-master-0.pg-master-headless.postgres.svc.cluster.local
Address: 10.1.45.45

Here is my code

MASTER_HOST=$(nslookup pg-master-0.pg-master-headlesss | awk '/^Address:/ {A=$2}; END {print A}');

echo $MASTER_HOST

Unfortunately, my output is:

10.152.183.10#53

Here I'm logged into the pod enter image description here then ran the nslookup that way.


Solution

  • If you want the 2nd "Address:" from the nslookup output, you can simply do:

    awk '/^Address/{n++; if (n==2){print $2; exit}}'
    

    Which checks if the line begins with Address, then increments a counter n++ and when n == 2 it outputs the second field and exits.

    Example Use/Output

    With your data in the file called nslookup.txt, you would receive the following:

    $ awk '/^Address/{n++; if (n==2){print $2; exit}}' nslookup.txt
    10.1.45.45
    

    Of course, using nslookup you would just pipe the output to awk. For example, if I wanted the IP of the machine valkyrie on my local subnet, I would use:

    $ nslookup valkyrie | awk '/^Address/{n++; if (n==2){print $2; exit}}'
    192.168.6.135
    

    Look things over and let me know if you have further questions.