1833866 Members
2294 Online
110063 Solutions
New Discussion

Context in HPUX grep

 
SOLVED
Go to solution
wojtek75
Frequent Advisor

Context in HPUX grep

HPUX B.11.11

Hi,

is there any command in HPUX that can work like GNU grep that shows context lines (a few lines preceeding and succeeding the selected line)? It looks like HPUX grep can't do that. Thank you in advance.
8 REPLIES 8
Pete Randall
Outstanding Contributor
Solution

Re: Context in HPUX grep

You can do it with sed:

# 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

Taken from Handy One-Liners for SED (attached).


Pete

Pete
wojtek75
Frequent Advisor

Re: Context in HPUX grep

Thanks, great but hard to understand without basic knowledge of sed. How can I get only one line before matching line?
James R. Ferguson
Acclaimed Contributor

Re: Context in HPUX grep

Hi:

For that matter, you could fetch and install GNU's 'grep' from the HP-UX Porting Center:

http://hpux.asknet.de/hppd/hpux/Gnu/grep-2.5.3/

Regards!

...JRF...
wojtek75
Frequent Advisor

Re: Context in HPUX grep

Hi,

sed is OK. I would appreciate the final sed command that prints only preceding line and doesn't print line numbers. How can I get it?
Patrick Wallek
Honored Contributor

Re: Context in HPUX grep

The following will print the line with the regexp and the line preceding:

sed -n -e '/regexp/{x;1!p;g;p;}' -e h filename


wojtek75
Frequent Advisor

Re: Context in HPUX grep

Thanks,

and is it possible to join these two lines together? I would like to have a preceding and matching line printed in one line.
James R. Ferguson
Acclaimed Contributor

Re: Context in HPUX grep

Hi:

> and is it possible to join these two lines together? I would like to have a preceding and matching line printed in one line.

# sed -n -e '/b/{x;1!p;g;p;}' -e h filename|paste -- - -

That's a double dash; whitespace; a single dash; whitespace; and another single dash.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Context in HPUX grep

>I would like to have a preceding and matching line printed in one line.

Modifying JRF's solution you can go sed crazy and do:
sed -n -e '/regexp/{H;g;s/\n/ /;p;}' -e h filename

(Note: It doesn't work too well if the pattern is on two sequential lines.)