Search code examples
regexterminalgreplookbehind

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.


Solution

  • 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.