Linux – How do I get a multiline string between two curly braces containing a specific search string?

How do I get a multiline string between two curly braces containing a specific search string?… here is a solution to the problem.

How do I get a multiline string between two curly braces containing a specific search string?

I’m looking for a quick and easy one-line code to extract all brace-delimited text containing search strings from a text block with search strings. I just went crazy on Googling myself, but everyone seems to post only about getting text between curly braces without searching for strings.

I have a large text file that reads as follows:

blabla
blabla {
  blabla
}
blabla
blabla {
  blabla
  blablaeventblabla
}
blabla

The vast majority of entries in parentheses do not contain the search string, which is “event”.

What I’m extracting is all the text between each set of curly braces (specifically including multi-line matches), but only if said text also contains a search string. So the output is as follows:

blabla {
  blabla
  blablaeventblabla
}

My linux command line is /usr/bin/bash. I’ve been trying various grep and awk commands but it just doesn’t work :

awk '/{/,/event/,/}/' filepath

grep -iE "/{.*event.*/}" filepath

I thought it would be simple because it’s a common task. What am I missing here?

Solution

This gnu-awk should work :

awk -v RS='[^\n]*{|}' 'RT ~ /{/{p=RT} /event/{ print p $0 RT }' file
blabla {
   blabla
   blablaeventblabla
}

RS='[^\n]*{\n|}' Any text that sets the input record delimiter to followed by { or }. RT is an internal awk variable that is set to match text based on RS regular expressions.

Related Problems and Solutions