get N lines above from the section obtained using sed

Viewed 71

need your help , I am stuck at some syntax error after applying sed, i need to pick 2-3 lines above including the section which i got after applying sed.

PLease help , Thanks in advance. here is my data

Line 1
Line 2
line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B
Line 11
Line 12
line 13
Line 14

Output

line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B

this is what i have tried so far.

sed  -e '/Section_A/,/Section_B/p' test.txt
sed  -e '/Section_A/1/,/Section_B/p' test.txt
5 Answers

You may use this awk:

awk '
/^Section_A$/ {s = pp ORS p}
s != "" {s = s ORS $0}
/^Section_B$/ {print s; s=""}
{pp=p; p=$0}' file

line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B

awk to the rescue!

$ awk '/^Section_A$/{print pp; print p; f=1} f; 
       /^Section_B$/{f=0} {pp=p; p=$0}' file

line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B

I sometimes find it conceptually easier to reverse the file. Then you're looking for 3 lines after "Section_A"

tac file \
| awk '
    /Section_B/,/Section_A/ {print; c=3; next}
    c-- > 0
  ' \
| tac
Line 2
line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B

With GNU awk for multi-char RS based on one possible interpretation of your requirements:

$ awk -v RS='([^\n]+\n){2}Section_A.*Section_B' 'RT{print RT}' file
line 3
Line 4
Section_A
blah1
blah2
blah3
blah4
Section_B
Related