Regex lookahead for 'not followed by' in grep

前端 未结 5 2023
忘了有多久
忘了有多久 2020-11-27 13:31

I am attempting to grep for all instances of Ui\\. not followed by Line or even just the letter L

What is the proper way to wr

5条回答
  •  鱼传尺愫
    2020-11-27 14:14

    If your grep doesn't support -P or --perl-regexp, and you can install PCRE-enabled grep, e.g. "pcregrep", than it won't need any command-line options like GNU grep to accept Perl-compatible regular expressions, you just run

    pcregrep "Ui\.(?!Line)"
    

    You don't need another nested group for "Line" as in your example "Ui.(?!(Line))" -- the outer group is sufficient, like I've shown above.

    Let me give you another example of looking negative assertions: when you have list of lines, returned by "ipset", each line showing number of packets in a middle of the line, and you don't need lines with zero packets, you just run:

    ipset list | pcregrep "packets(?! 0 )"
    

    If you like perl-compatible regular expressions and have perl but don't have pcregrep or your grep doesn't support --perl-regexp, you can you one-line perl scripts that work the same way like grep:

    perl -e "while (<>) {if (/Ui\.(?!Lines)/){print;};}"
    

    Perl accepts stdin the same way like grep, e.g.

    ipset list | perl -e "while (<>) {if (/packets(?! 0 )/){print;};}"
    

提交回复
热议问题