Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: multiple lookbehinds

I'm struggling with this regex for days. I have this text:

alias -g NULL="> /dev/null 2>&1"    # redirect output
test                                # don't match
alias l="ls -lahGF"                 # list all
PROMPT=$'$FG[237]'                  # don't match

And I want to match NULL and l using grep or other terminal commands. Is it possible to directly match them without using groups?

I tried using (?<=^alias )(?<=-g).+ with no result.

like image 992
Iulian Onofrei Avatar asked Feb 11 '26 03:02

Iulian Onofrei


1 Answers

You could use the below grep command which uses a PCRE regex.

grep -oP '^alias(?:\s+-g)?\s+\K[^=]+(?==)' file

OR

grep -oP '^alias(?:\s+-g)?\s+\K\w+' file

OR

$ grep -oP '^alias(?:\s+-g)?\s+\K[^=]+' file
NULL
l

\K discards the previously matched characters from printing at the final. \K keeps the text matched so far out of the overall regex match.

like image 69
Avinash Raj Avatar answered Feb 12 '26 15:02

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!