Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get multi-line string between two braces containing a specific search string?

Tags:

linux

bash

I'm looking for a quick and easy one-liner to extract all brace-delimited text-blocks containing a search string from a text file. I've just about googled myself crazy on this, but everyone seems to be only posting about getting the text between braces without a search string.

I've got a large text file with contents like this:

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

The vast majority of bracketed entries do not contain the search string, which is "event".

What I am trying to extract are all text (especially including multi-line matches) between each set of curly braces, but only if said text also contains the search string. So output like this:

blabla {
  blabla
  blablaeventblabla
}

My linux command line is /usr/bin/bash. I've been trying various grep and awk commands, but just can't get it to work:

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

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

I was thinking this would be really easy, as it's a common task. What am I missing here?

like image 354
leu Avatar asked Oct 16 '25 12:10

leu


1 Answers

This gnu-awk should work:

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

RS='[^\n]*{\n|}' sets input record separator as any text followed by { OR a }. RT is the internal awk variable that is set to matched text based on RS regex.

like image 84
anubhava Avatar answered Oct 19 '25 02:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!