manus
manus

Reputation: 41

Issue in multiline matching using perl one liner

I am trying to use Perl one liner, for matching a multi line pattern. My file "new" will look like something below.

foo
bar
foo1
bar1
go

bye
bar2

Intention is to match first four lines, which is between foo and bar1.

My one liner is given below:

perl -0777 -n -e 'm/^foo.+?bar1/s && print' new

I am reading the file as a whole instead of line by line using -0777. Also, I have given /s modifier for making "." match a "\n" also. But this one liner is not serving the purpose. It is matching the enitre file here.

I may be missing something very fundamental here. Can I have the help of experts on this, as this is something really annoying me for so long?

Upvotes: 0

Views: 623

Answers (2)

Miller
Miller

Reputation: 35198

Another solution would be to use a range .. while still processing the file line by line:

perl -ne 'print if /^foo$/../^bar1$/' new

This may not work entirely as you want though because

  1. It will print starting at foo to the end of the file if no bar1 exists.
  2. If there is more than one range of foo to bar1 it will print each of them.

Upvotes: 0

Lee Duhem
Lee Duhem

Reputation: 15121

Try this:

perl -0777 -n -e 'm/^(foo.+?bar1)/s && print $1' new

By default, print will output $_, and the value of that variable is the whole file in your case.

Upvotes: 1

Related Questions