0

I am trying to grep the word that comes after the match "name:"

Her name: Ana Frost. I know we are meant to be.
Her name: Beth Cooper. I know we are meant to be.

I want my output to be:

Ana
Beth

I tried using the command below but it didn't work:

grep -i '(?<=name:\s)\w+'

Is there a way to do this without the positive lookbehind or make the Unix shell somehow recognize it? Thanks.

Inian
  • 80,270
  • 14
  • 142
  • 161
Klyde
  • 1
  • 2

1 Answers1

3

I see no reason to use any lookbehind. Just find the word after name:.

With GNU sed:

sed 's/.*name: \([A-Z][a-z]\+\).*/\1/'

With any POSIX sed:

sed 's/.*name: \([A-Z][a-z]\{1,\}\).*/\1/'

With grep with perl regex:

grep -Po 'name: \K\w+'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 2
    Under Mac OSX there is no grep with perl regex and the sed "\+" escape does not work. So as an alternate for OSX write: sed 's/.*name: \([A-Z][a-z]\{1,\}\).*/\1/' – Tom Freudenberg Aug 24 '20 at 22:18
  • What does the \K stand for? – Klyde Aug 25 '20 at 11:09
  • `-o` prints the matched pattern. `\K` is part of perl regex, it "clears" the current matching pattern/buffer. So `grep 'name: \w+'` would print `name: Ana`. The `\K` "clears" the `name:` part from matchin pattern, making `grep` printing only Ana. It's commonly used like `grep -Po 'something \Koutput this'` – KamilCuk Aug 25 '20 at 11:18
  • Thanks! That was very helpful! – Klyde Aug 25 '20 at 16:23