Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep a block of text delimited by two key lines

I have a text file that contains text blocks roughly formatted like this:

Beginning of block
...
...
...
.........some_pattern.......
...
...
End of block

Beginning of block
...
... etc.

The blocks can have any number of lines but always start with the two delimiters. What I'd like to do is match "some_pattern" and print the whole block to stdout. With the example above, I would get this only:

Beginning of block
...
...
...
.........some_pattern.......
...
...
End of block

I've tried with something like this but without success:

grep "Beginning of block\n.*some_pattern.*\n.*End of block"

Any idea how to do this with grep? (or maybe with some other tool)

like image 923
laurent Avatar asked Nov 12 '13 10:11

laurent


2 Answers

I guess awk is better for this:

awk '/Beginning of block/ {p=1};
     {if (p==1) {a[NR]=$0}};
     /some_pattern/ {f=1};
     /End of block/ {p=0; if (f==1) {for (i in a) print a[i]};f=0; delete a}' file

Explanation

It just prints when the p flag is "active" and some_pattern is matched:

  • When it finds Beginning of block, then makes variable p=1 and starts storing the lines in the array a[].
  • If it finds some_pattern, it sets the flag f to 1, so that we know the pattern has been found.
  • When it finds End of block it resets p=0. If some_pattern had been found since the last Beginning of block, all the lines that had been stored are printed. Finally a[] is cleared and f is reset; we will have a fresh start when we again encounter Beginning of block.

Other test

$ cat a
Beginning of block
blabla
.........some_pattern.......
and here i am
hello
End of block

Beginning of block
...
... etc.
End of block
$ awk '/Beginning of block/ {p=1}; {if(p==1){a[NR]=$0}}; /some_pattern/ {f=1}; /End of block/ {p=0; if (f==1) {for (i in a) print a[i]}; delete a;f=0}' a
Beginning of block
blabla
.........some_pattern.......
and here i am
hello
End of block
like image 158
fedorqui 'SO stop harming' Avatar answered Oct 14 '22 13:10

fedorqui 'SO stop harming'


The following might work for you:

sed -n '/Beginning of block/!b;:a;/End of block/!{$!{N;ba}};{/some_pattern/p}' filename
like image 29
devnull Avatar answered Oct 14 '22 14:10

devnull