Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get N lines above from the section obtained using sed

Tags:

grep

sed

awk

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
like image 594
Prayag Avatar asked Dec 05 '25 04:12

Prayag


1 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
like image 54
anubhava Avatar answered Dec 07 '25 20:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!