0

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.

3
  • 2
    What is the $ after perl -w -e for? Commented Sep 11, 2014 at 18:42
  • @i alarmed alien it's the bash escape character. Am I using it wrong? I thought I was supposed to do $'\r' $'\n' etc Commented Sep 12, 2014 at 2:02
  • As I said in my answer, the $ is why your code was not working. Commented Sep 12, 2014 at 8:03

2 Answers 2

5

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.
Sign up to request clarification or add additional context in comments.

2 Comments

The "line" we're speaking of is just the entire contents of STDIN, correct?
Correct. In this case a line is the entire file because it's set to slurp mode. If there were two files queued up, there would be two "lines".
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.