It turns out that it's quite tricky to emulate -B, because of the issues that crop up when you have matching lines following each other directly. This pretty much disallows using any sort of single-pass-through file scanning.
I realized this while playing around with the following approximation:
perl -pe 'if(/search_term/) {print foreach @A; print ">"; $B=4}; shift @A if push(@A, $_)>7; $_ = "" unless ($B-- > 0);' target_file
This will work roughly correctly as grep -A7 -B3 would, with the caveat described in the first paragraph.
An alternative (also single-file) solution to this issue is to use perl to feed sed a command string:
sed -n `perl -pe '$_=(/search_term/?sprintf("%d,%dp;", $.-3,$.+4):"")' file` file
-C
switch. – Lazer Apr 13 '11 at 01:42GNU > /usr/local
. The GNU programs have lots of very useful extensions, and are designed to avoid arbitrary restrictions (but you do pay dearly in size and sometimes performance). Many propietary systems have "unofficial" package repositories with GNU and other tools. The "partner" won't tell you about them, even when they are managed by the vendor... – vonbrand Jan 23 '13 at 14:36