1

I want search for a string and to pull all the lines between two patterns(including the pattern).

START#1

Name S

101

Frankfurt_1_1

19

A+

Street


END


START#2

Name B

104

Berlin

20

A+

Street


END



START#100

Name C

107

Berlin

21

A+

Street

END



START#24

Name D

110

Frankfurt_1_1

21

A+



END

If I grep Frankfurt

Then it has to display all the lines between START and END(including START AND END) like :

START#1

Name S

101

Frankfurt_1_1

19

A+

Street


END


START#24

Name D

110

Frankfurt_1_1

21

A+

Street


END

Command which I used :

cat file | awk '/START/,/END/' | grep -p Frankfurt

But it didn't work.

  • Blank lines does present in file or not required ? – Rahul Apr 21 '16 at 9:46
  • @arzyfex blank lines are required . – user4432340 Apr 21 '16 at 9:50
  • how many blank lines present between each line ? is it uniform or randomly created ? – Rahul Apr 21 '16 at 9:54
  • @arzyfex the blank lines count may vary. It's randomly created – user4432340 Apr 21 '16 at 9:57
1

Not sure awk is the correct tool for that job since your search is over multiple lines based. I would think it's a job for perl. Going through your file you can use (similar to your awk statement):

if (/^START/ .. /^END/){}

in there you store your lines in an array, that you're going to print if say Frankfurt is met (use a boolean here):

push @lines, $_;
if (/Frankfurt/)
        $toPrint = 1;

and in all cases when you're out of your pattern you, print the array if your boolean is true, don't print otherwise, empty you're array.

0

Definitely we can use awk, try this one

awk -v RS="END" '$0~/Frankfurt/{print $0 RS}' file

  • it's not working . Nothing is displayed – user4432340 Apr 21 '16 at 14:57
  • @user4432340 : How is it possible.. I have tried this on my box, it displays what you needed. make sure you enter correct filename. – Rahul Apr 21 '16 at 15:13
  • START# Name S 101 Frankfurt_1_1 19 A+ Street END ND START# Name D 110 Frankfurt_1_1 21 A+ It's giving this output note: i have replaced START with START# and Frankfurt with Frankfurt_1_1 – user4432340 Apr 21 '16 at 15:39
  • @user4432340 please update this in question. I don't understand what you are trying to show. There is update button on below of your question. Please update it. – Rahul Apr 21 '16 at 16:13
  • I have updated the question. – user4432340 Apr 21 '16 at 17:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.