Hi.
Given the characterisitcs of this problem, a 2-step grep can be used, but the grep needs to be able collect 1 line before and after matched lines. For example, with GNU grep:
#!/usr/bin/env bash
# @(#) s3 Demonstrate match across lines, grep.
# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
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 grep
FILE=${1-data1}
pl " Input data file $FILE:"
cat $FILE
pl " Results, grep for RITE AID back to ST*82 across lines:"
if grep -F -B1 'RITE AID' $FILE |
grep -q -F -A1 'ST*82'
then
printf "$FILE\n"
fi
FILE=data3
pl " Input data file $FILE:"
cat $FILE
pl " Results, grep for RITE AID back to ST*82 across lines:"
if grep -F -B1 'RITE AID' $FILE |
grep -q -F -A1 'ST*82'
then
printf "$FILE\n"
fi
exit 0
producing:
$ ./s3
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 5.0.8 (lenny, workstation)
bash GNU bash 3.2.39
grep GNU grep 2.5.3
-----
Input data file data1:
ISA*00* 00 *ZZ*NATIONSBANK *14*0030020520500 *140918*1200*U*00401*000006436*0*P*^
GS*RA*014578892*IGIHCJEEJ*20140918*1200*6442*X*004010
ST*820*000006482
N1*PR*RITE AID HDQTRS. CORP.*1*014578892
-----
Results, grep for RITE AID back to ST*82 across lines:
data1
-----
Input data file data3:
ISA*00* 00 *ZZ*NATIONSBANK *14*0030020520500 *140918*1200*U*00401*000006436*0*P*^
GS*RA*014578892*IGIHCJEEJ*20140918*1200*6442*X*004010
ST*820*000006482
not a matching line
N1*PR*RITE AID HDQTRS. CORP.*1*014578892
-----
Results, grep for RITE AID back to ST*82 across lines:
The way this works is that for each line that matches the second pattern, we capture it and the preceding line. Those pairs of lines are piped into a second grep, which lists the pairs only if the first pattern occurs.
Note that the second data file, data2, has an intervening line between the two patterns of interest, which should disqualify that file from being listed and it does. I'm sure it's possible to construct pathological cases where this fails, but then the sample provided would not have been representative.
I have not tested this extensively, but it seems to make sense for the problem at hand.
Best wishes ... cheers, drl