Multi-line group capturing between braces

I have something like this in a file testtt:

{It captures this! }
// question: 2572410 name: Question 2
::Question 2::[html] Is it going to be -40 tomorrow?
{
It can't
capture this!!! why?
}

when I do:

grep -o '{\([^}]*\)}' testttt

It can't capture the multi-line braces. Any help to modify it in way that it could capture both would be apppreciated!

PS. I have also tested the given solution from: How do I grep for multiple patterns on multiple lines?and it gives the following error:

grep: unescaped ^ or $ not supported with -Pz

You can find the text file of the output and file contents here

5

2 Answers

By default, grep reads and processes single lines.

In newer versions of grep, you can use the -z option to tell it to consider its input to be null separated instead of newline separated; since your input doesn't have null terminations, that's essentially equivalent to perl's 'slurp' mode. So you could do

$ grep -zPo '{[^}]*}' testttt
{It captures this! }
{
It can't
capture this!!! why?
}

or, more perlishly, using a .*? non-greedy match with (?s) to include newlines in .

$ grep -zPo '(?s){.*?}' testttt
{It captures this! }
{
It can't
capture this!!! why?
}

Alternatively, if pcregrep is available,

$ pcregrep -Mo '(?s){.*?}' testttt
{It captures this! }
{
It can't
capture this!!! why?
}
0

In order to trigger multi-line search with grep you have to add few option more, so try:

 grep -Pzo '(?s){.*?}' testttt

Solution with nice explanation can be found (and is stolen:) ) from stackoverflow.

If you have pcregrep you may find it more useful in general case as it supports PERL 5 regex.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like