1

I'm trying to extract part of a string using grep with a regular expression. I already tested the regex using regexr and it's working. I'm on macOS.

This is my code:

echo -e '"HI":"Hola!"' | grep -o '(?=[^\"]).+?(?=":")'

If I try to use the -P option it shows the usage description for grep:

usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
        [-e pattern] [-f file] [--binary-files=value] [--color=when]
        [--context[=num]] [--directories=action] [--label] [--line-buffered]
        [--null] [pattern] [file ...]

I want to get HI as the output. Do I need to pipe the grep output or am I missing something else?

Thanks

  • You did not test the regex with the compatible regex tester. POSIX BRE regex does not support lookarounds. Did you mean to use `echo -e '"HI:"Hola!""' | grep -Po '(?<=").+?(?=:")'`? – Wiktor Stribiżew Apr 03 '19 at 14:08
  • You're right, I use [regexr](https://regexr.com) to test. The `-P` option doesn't work, I'm on macOS. I'm gonna update the problem description. – Gonzalo Castillo Apr 03 '19 at 17:59
  • I fixed the problem with the `-P` option. I had to install grep with `brew`. Theres was an issue with the `grep` version on macOS. The resulting code is this: ```echo -e '"HI":"Hola!"' | ggrep -Po '(?=[^\"]).+?(?=":")'``` – Gonzalo Castillo Apr 03 '19 at 18:36

2 Answers2

1

With GNU-grep :

$ echo '"HI:"Hola!""' | grep -oP '\w+(?=:)'
HI

or with :

$ echo '"HI:"Hola!""' | perl -lne 'print $& if /\w+(?=:)/'
HI

look around explained

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

If you don't have a perl-compatible version of grep , try sed -

$: echo -e '"HI:"Hola!""' | sed -En '/".*?:"/ { s/.*"(.*?):".*/\1/; p; }'
HI

This grabs the first occurance of everything between " and :". Please clarify your parameters if that's not right.

Also, you could just use perl. :)

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36