awk find a string, print the line 2 lines below it

I am parsing a nagios config, searching for a string, and then printing the line 2 lines later (the "members" string). Here's the data:

define hostgroup{
    hostgroup_name    chat-dev
    alias        chat-dev
    members        thisisahostname
    }

define hostgroup{
    hostgroup_name    chat-qa
    alias        chat-qa
    members        thisisadifferenthostname
    }

I have the following one-liner which works:

$ awk -v hgn="chat-qa" '{ if ($1 == "hostgroup_name" && $2 == hgn ) { getline;getline;print $0 } }' testfile
    members        thisisadifferenthostname

Is there a better way to do this? First, the double getline seems a little cheesy to me. Second, what I'd really like to do is, once I find my string, search line by line after it until you find a line in which $1=="member" and then print that line. That way, if that line isn't exactly 2 lines later I'll still find it.

Thanks,

MG

First a little shortening :wink: :

awk '$1=="hostgroup_name" && $2==hgn {getline;getline;print}' hgn="chat-qa" infile

or you can use sed:

hgn="chat-qa"; sed -n "/hostgroup_name.*$hgn/{n;n;p}" infile

To find members without the double getline:

awk '$1=="hostgroup_name" && $2==hgn{p=1} $1=="members" && p{p=0;print}' hgn="chat-qa" infile