Need to print between patterns AND a few lines before

I need to print out sections (varying numbers of lines) of a file between patterns. That alone is easy enough:

sed -n '/START/,/STOP/'

I also need the 3 lines BEFORE the start pattern. That alone is easy enough:

grep -B3 START

But I can't seem to combine the two so that I get everything between the patterns PLUS the 3 lines before the start of the pattern. I'm sure it's easy enough and I'm just not thinking it through, but it's been a long day. Help?

Hi.

For small enough files, old line editor ed or ex can be used:

#!/usr/bin/env bash

# @(#) s1	Demonstrate ex ability to do line address arithmetic.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C ex

FILE=${1-data1}

pl " Input data file $FILE:"
cat $FILE

pl " Results, corge-3 through garble:"
ex $FILE <<EOF
/corge/-3,/garble/p
q
EOF

exit 0

producing:

% ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0.8 (lenny) 
bash GNU bash 3.2.39
VIM ex 7.1

-----
 Input data file data1:
foo
bar
baz
qux
quux
corge
grault
garble
warg
fred
plugh
xyzzy
thud

-----
 Results, corge-3 through garble:
baz
qux
quux
corge
grault
garble

See man ed for details.

Best wishes ... cheers, drl

1 Like
awk ' { print substr($0,index($0,"START")-3,index($0,"STOP")-index($0,"START")+3); } '

My bad, I misread the requirement, above command will work only for character position, not for lines.