Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive/Negative lookahead with grep and perl

my login.txt file contains following entries

abc def
abc 123
def abc
abc de
tha ewe

when i do the positive lookahead using perl, i'm getting the following result

cat login.txt | perl -ne 'print if /(?)abc\s(?=def)/'
abc def

when i use grep i'm getting the following result

cat login.txt | grep -P '(?<=abc)\s(?=def)'
abc def

negative lookahed results as follows from perl and grep.

 cat login | perl -ne 'print if /(?)abc\s(?!def)/'
abc 123
def abc
abc de

grep result

cat login.txt | grep -P '(?<=abc)\s(?!def)'
abc 123
abc de

perl matched the def abc for the negative lookahead. but it shouldn't matched def abc, as i'm checking abc then def pattern. grep returning the correct result.

is something missing in my perl pattern ?

like image 561
Tharanga Abeyseela Avatar asked Dec 18 '13 11:12

Tharanga Abeyseela


People also ask

Does grep have lookahead?

grep in macOS does not support lookahead.

Does grep support Lookbehind?

find (both the GNU and BSD variants) do not support lookahead/lookbehind. GNU grep only supports the POSIX basic and extended regular expression variants as well as a couple of others.

What is positive and negative lookahead?

Positive lookahead: (?= «pattern») matches if pattern matches what comes after the current location in the input string. Negative lookahead: (?! «pattern») matches if pattern does not match what comes after the current location in the input string.

Does SED support Lookbehind?

I created a test using grep but it does not work in sed . This works correctly by returning bar . I was expecting footest as output, but it did not work. sed does not support lookaround assertions.


1 Answers

grep does not include the newline in the string it checks against the regex, so abc\s does not match when abc is at the end of the line. chomp in perl or use the -l command line option and you will see similar results.

I'm not sure why you were making other changes between the perl and grep regexes; what was the (?) supposed to accomplish?

like image 195
ysth Avatar answered Oct 31 '22 05:10

ysth