If your grep
doesn't have -A
, -B
and -C
, then this sed
command may work for you:
sed -n '1bb;:a;/PATTERN/{h;n;p;H;g;bb};N;//p;:b;99,$D;ba' inputfile > outputfile
where PATTERN
is the regular expression your looking for and 99
is one greater than the number of context lines you want (equivalent to -C 98
).
It works by keeping a window of lines in memory and when the regex matches, the captured lines are output.
If your sed
doesn't like semicolons and prefers -e
, this version may work for you:
sed -n -e '1bb' -e ':a' -e '/PATTERN/{h' -e 'n' -e 'p' -e 'H' -e 'g' -e 'bb}' -e 'N' -e '//p' -e ':b' -e '99,$D' -e 'ba' inputfile > outputfile
For your line range output, this will work and will finish a little more quickly if there are a large number of lines after the end of the range:
sed -n '100000,20000p;q' inputfile > outputfile
or
sed -n -e '100000,20000p' -e 'q' inputfile > outputfile