Remix.run Logo
cafeinux 7 months ago

I usually use PCRE mode and prepend what I want to be displayed with `\K` (and append a lookahead if needed):

  ~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d'
  bar1
  bar2
  ~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d(?= baz)'
  bar1
  ~ $ echo "foo bar1 baz foo bar2" | grep -oP 'foo \Kbar\d(?=$)'
  bar2
Of course, it implies using a version of `grep` supporting the `-P` option. Notably, MacOS doesn't by default, although if -P is utterly needed, there are ways to install gnu-grep or modify the command used to achieve the same result. Your way is perhaps more cross-platform, but for my (very personal) use cases, mine is easier to remember and needs no setup.

Edit: worst case, piping to `cut` or `awk` can also be a solution.

Joker_vD 7 months ago | parent [-]

Ah, I knew about the \K to cut things before the match, but I could never find how to cut away the things after. But it exists and it's (?=... Well, better late than never.

> worst case, piping to `cut` or `awk` can also be a solution.

Yeah, I've used that too, and that's how I ended with writing the script down: constantly piping things through the second filter with yet another stupid regex that needs tinkering as well... isn't there a way to reuse the first regex, somehow? Hmm, don't the patterns in the sed's "substitute" use the same syntax as the grep does?.. They do! How convenient.