0

Trying to match before the start, and right after the end of my string. This question seemed up my alley: How to use sed/grep to extract text between two words?

I managed to match the start (1st match). But for the end (2nd match), it matched the last match.

Sample string:

Bob said that John is nice, which makes Bob nice.

I want to get "John is", so I look for the string between "Bob said"

baz="Bob said that John is nice, which makes Bob nice."
echo `echo "$baz" | sed 's/Bob said that \(.*\) nice/\1/'`
#result: John is nice, which makes Bob.

It matched the last "nice" instead of the next nice. Is there any way to match the next "nice"?

Community
  • 1
  • 1
Buttle Butkus
  • 9,206
  • 13
  • 79
  • 120
  • 1
    `*` is [greedy](https://stackoverflow.com/documentation/regex/429/greedy-and-lazy-patterns#t=201610280926056053242).. try `echo "$baz" | sed 's/Bob said that \(.*\) nice,.*/\1/'` – Sundeep Oct 28 '16 at 09:26
  • Many of the answers in the duplicate are problematic for the more general case (i.e. there isn't a single character you can exclude to make a complex regex non-greedy) but switching to e.g. Perl (or any other tool which does in fact support non-greedy regex) solves that elegantly. – tripleee Oct 28 '16 at 09:37
  • @Sundeep you changed the matching text from "nice" to "nice,", right? You are using the fact that the 2nd nice has "." instead of "," That would work in my example but not with my actual problem text. – Buttle Butkus Oct 28 '16 at 09:38
  • @tripleee I am willing to use any tool I have on my system. Let me see. – Buttle Butkus Oct 28 '16 at 09:39
  • 1
    @ButtleButkus, yup, that was just a demonstration.. and as the answers in duplicate question shows, you'll need to handle each case separately... for ex: `grep -oP 'Bob said that \K.*?(?= nice)'` will also work in this case – Sundeep Oct 28 '16 at 09:42
  • @Sundeep thanks for that. I was unfamiliar with the `-oP` options. Is the `K` what makes it non greedy? It's very hard to search google for single letters. – Buttle Butkus Oct 28 '16 at 09:51
  • 1
    @Sundeep thanks very much. I think perhaps I should spend a few days just mastering the heck out of that. – Buttle Butkus Oct 28 '16 at 10:02

0 Answers0