Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

Script "Pattern matching help"

SOLVED
Go to solution
Prashant Zanwar_4
Respected Contributor

Script "Pattern matching help"

I have a file having following contents:

Hostname:
Comments:

This may contain several lines arranged in fashion as given above.

I want to grab those hosts having development in comment field.

If I try doing it using egrep, Hostname line is anyways getting included even if it is not development box. What can be the turn around. I appreciate all your help.

Thanks
Prashant
"Intellect distinguishes between the possible and the impossible; reason distinguishes between the sensible and the senseless. Even the possible can be senseless."
4 REPLIES
Pete Randall
Outstanding Contributor
Solution

Re: Script "Pattern matching help"

Prashant,

You could adapt this hint from "Handy One Liners for Sed" (attached):

# print 1 line of context before and after regexp, with line number
# indicating where the regexp occurred (similar to "grep -A1 -B1")
sed -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h


Pete

Pete
Rodney Hills
Honored Contributor

Re: Script "Pattern matching help"

How about "awk"-

awk '/^Hostname/{h=$0};/^Comments: Devel/{print h}' yourfile

HTH

-- Rod Hills
There be dragons...
Prashant Zanwar_4
Respected Contributor

Re: Script "Pattern matching help"

That was great. I have did it using sed. Just nice.

Thanks and regards
Prashant
"Intellect distinguishes between the possible and the impossible; reason distinguishes between the sensible and the senseless. Even the possible can be senseless."
Highlighted
Tim D Fulford
Honored Contributor

Re: Script "Pattern matching help"

perl is also an option

perl -ane 'if (m/Hostname/) {$hst="@F"}; if (m/Comments: Development/) {print "$hst \n"}' file

Just another way of doing the same in a funkier/newer language.

Redards

-