Search code examples
grepmatchtextblock

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)


Solution

  • The following might work for you:

    sed -n '/Beginning of block/!b;:a;/End of block/!{$!{N;ba}};{/some_pattern/p}' filename