-1

I am trying to extract set of lines between specific patterns in bash.

My input file:

=========
a
b
ven
c
d
=========
abc
def
venkata
sad
dada
=========

I am trying to extract only the lines between two ======= which contains the pattern venkata in between. ie., the second section in the above eg (abc ... dada).

I have tried sed, but it does not give what I need exactly.

I tried splitting this task to getting lines above venkata and the lines below it separately.

Using sed -n -e '/=====/,/venkata/p' gives starting from the beginning of the input, which is not what I need.

Any thoughts ?

Edit: The number of lines between ======= can be of any number and venkata can be at any line, not necessarily the exact middle.
There can be multiple words,numbers,symbols in each line. This is just a sample

Edit 2: How to select lines between two marker patterns which may occur multiple times with awk/sed accepted answer is close, but gives the output from the first match. That is not what I am looking for.
Based on the command in the answer of that question, it would set the flag when the first ==== is found. I need the ==== just before venkata, which need not be the very first match.
That answer does not help me solve my problem

Venkata Krishna
  • 1,768
  • 2
  • 14
  • 21

2 Answers2

0

Using gnu-awk you can do this:

awk -v RS='={2,}\n' -v ORS= '/venkata/' file

abc
def
venkata
sad
dada

If you don't have gnu-awk then use:

awk '/={2,}/{if (s && data ~ /venkata/) printf "%s", data; s=1; data=""; next} s{data = data $0 RS}' file
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • If you don't have `gnu-awk` then use: `awk '/={2,}/{if (s && data ~ /venkata/) printf "%s", data; s=1; data=""; next} s{data = data $0 RS}' file` – anubhava Jan 31 '18 at 12:17
  • I dont have gnu-awk, I tried the respective solution. But it didn't work out. It didn't return anything back. I wasn't clear with the logic to try and debug the solution given. – Venkata Krishna Feb 01 '18 at 05:04
  • [Check this working demo with suggested alternate `awk` command](https://ideone.com/sYMyca) If you have different sample data then edit the question and I will investigate further. – anubhava Feb 01 '18 at 07:03
0

Using grep you can accomplish the same:

cat infile | grep -A 2 -B 2 "venkata"

The options -A and -B print a number of trailing and leading lines respectively.

As pointed out by @Jan Gassen, if you want the same amount of lines unde and above the matching pattern, you can make it even simpler by:

cat infile | grep -C 2 "venkata"
M. Becerra
  • 639
  • 6
  • 21