Re: Script "Pattern matching help" (41 Views)
Reply
Respected Contributor
Prashant Zanwar_4
Posts: 772
Registered: ‎04-30-2004
Message 1 of 5 (41 Views)
Accepted Solution

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."
Please use plain text.
Outstanding Contributor
Pete Randall
Posts: 16,201
Registered: ‎11-03-1996
Message 2 of 5 (41 Views)

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
Please use plain text.
Honored Contributor
Rodney Hills
Posts: 1,679
Registered: ‎09-09-1996
Message 3 of 5 (41 Views)

Re: Script "Pattern matching help"

How about "awk"-

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

HTH

-- Rod Hills
There be dragons...
Please use plain text.
Respected Contributor
Prashant Zanwar_4
Posts: 772
Registered: ‎04-30-2004
Message 4 of 5 (41 Views)

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."
Please use plain text.
Honored Contributor
Tim D Fulford
Posts: 1,424
Registered: ‎12-11-2000
Message 5 of 5 (41 Views)

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

-
Please use plain text.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation