Syl Syl - 1 month ago 5x
Bash Question

How to extract a value from a string using regex and a shell?

I am in shell and I have this string:

12 BBQ ,45 rofl, 89 lol

Using the regexp:
\d+ (?=rofl)
, I want
as a result.

Is it correct to use regex to extract data from a string? The best I have done is to highlight the value in some of the online regex editor. Most of the time it remove the value from my string.

I am investigating
, but all I get is syntax errors.

How can I manage to extract 45 in a shell script?


You can do this with GNU grep's perl mode:

echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o

-P means Perl-style, and -o means match only.