loop
loop

Reputation: 3590

perl binary stdin multiline regex

I am trying to match a pattern over multiple lines. I would like to ensure the line I'm looking for ends in \r\n and that there is specific text that comes after it at some point. I already tried in grep but it doesn't work without the -P switch which some versions don't have. So now I'm trying in perl.

I can't figure out why this doesn't work:

echo -e -n "ab\r\ncd" | perl -w -e $'binmode STDIN;undef $/;$_ = <>;if(/ab\r\ncd/){print "test"}'

I enabled slurp mode globally (undef $/;) which is sloppy but fine for this (I'll certainly take any better ideas). If I just do a print and pipe it to od I can see that $_ holds the correct bytes. The regex should match those same bytes but doesn't work for some reason. I can match ab\r but not ab\r\n etc.

Upvotes: 0

Views: 943

Answers (2)

i alarmed alien
i alarmed alien

Reputation: 9530

Works for me:

echo -e -n "ab\r\ncd" | perl -w -e 'binmode STDIN;undef $/;$_ = <>;if(/ab\r\ncd/){print "test"}';

Output:

test

You had a stray $ before the perl code.

Upvotes: 1

Miller
Miller

Reputation: 35208

Your code works if you remove the stray $ from the beginning of your code section.

However, it can be tightened up by using some command line switches such as -0777:

echo -e -n "ab\r\ncd" | perl -0777 -ne 'print "test" if /ab\r\ncd/'

Outputs:

test

Switches:

  • -0777: Slurp the entire file as documented in perlrun
  • -n: Creates a while(<>){...} loop for each “line” in your input file.
  • -e: Tells perl to execute the code on command line.

Upvotes: 5

Related Questions