Opposite of \K, to keep the stuff right

7,365

In this case, zero-width lookahead (?=...) does what you want:

$ echo foo bar buzz | grep -Po "foo \Kbar(?= buzz)"
bar

It does require some extra parentheses. There is no single-character escape for lookahead the way there is for \K.

\K is really just a zero-width lookbehind for everything so far, so this is also equivalent to

echo foo bar buzz | grep -Po "(?<=foo )bar(?= buzz)"

which I find easier to follow personally.

Share:
7,365

Related videos on Youtube

kenorb
Author by

kenorb

I'm a DevOps guy, also IT engineer programming in anything that has syntax. "Life is about making a big impact in the other people's lives."

Updated on September 18, 2022

Comments

  • kenorb
    kenorb over 1 year

    On the perlre's extended patterns page we can read about \K:

    Keep the stuff left of the \K, don't include it in $&

    Here is the practical example using GNU grep (which actually keeps stuff right of the \K):

    $ echo "foo bar buzz" | grep -Po "foo \Kbar buzz"
    bar buzz
    

    Is there any opposite sequence of \K?

    For example to print just bar, like:

    $ echo "foo bar buzz" | grep -Po "foo \Kbar\X buzz"
    bar
    
    • done
      done about 6 years
      Is sed also valid? echo "foo bar buzz" | sed -E '/foo (bar) buzz/s//\1/'
    • roaima
      roaima about 6 years
      @isaac I don't see anything in that duplicate that answers the question here.
    • done
      done about 6 years
      @roaima The first answer in there presents the same zero-width lookahead (?=...) grep -oP 'foo \K\w+(?= bar)' test.txt that the accepted answer use here. It seems to me that the answer there also solve the issue here.
  • smw
    smw about 6 years
    IIRC the difference between pat\K and (?<=pat) is that \K permits variable-length lookbehind - AFAIK there's no such restriction for the lookahead version (which is perhaps why there's no lookahead equivalent of \K)
  • Michael Homer
    Michael Homer about 6 years
    That's my understanding as well, and that it can be more efficient than regular lookbehind (because there's no extra backtracking?), so it can be preferable sometimes.