I am struck with the below requirement. I need to grep a particular pattern in a file and then print next n lines of it for further processing.
I have used the below code
Hi Corona,
Thanks for the reply. My system is Solaris . But i need this for AIX too
I am getting error when used with awk and no output when used with nawk as below
$ awk 'PAT ~ $0 { N=LINES } (N--) > 0' LINES=5 PAT="ISEND" sqloutput1.log
awk: syntax error near line 1
awk: bailing out near line 1
$ nawk 'PAT ~ $0 { N=LINES } (N--) > 0' LINES=5 PAT="ISEND" sqloutput1.log
$
Some general alternatives, as opposed to single-purpose solutions:
Print lines above, below pattern-matched line (context, window); "only" string matching pattern
1) GNU grep -A -B; ggrep on some Solaris
2) peg, a perl script, does not use "-o" like GNU grep;
allows -A, -B
3) ack, a perl script, can use "-o" like GNU grep; allows -A,
-B
4) cgrep does not use "-o" like GNU grep; allows -nline,
+nline for context like GNU grep -A, -B
5) bool, prints context in bytes
6) xtcgrep, extension of CPAN grep; allow -C context; allows -o;
complicated calling sequence; http://freecode.com/projects/greppm
Problem solved. But the previous sed solution needs a fix; (at least on Solaris) it does not print at the end of a file, because the N command terminates the script. Therefore, each N is to be preceded by a $p .
The following works with a number for the trailing lines (here: 3).
sed -e '/^<search-pattern>/!d;:L' -e '$p;N;s/\n/&/3;t' -e 'bL' file
---------- Post updated at 10:19 AM ---------- Previous update was at 10:14 AM ----------
Hmm interesting, GNU sed prints at the end of the file, so the $p would print twice...
Which sed is correct?
You objection is correct and it was my bad not to think my solution through to the end. GNU-sed - as it is so often is the case - gets it wrong (again).