Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This gnu-awk should work:

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

RS='[^ ]*{ |}' 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...