in reply to print data between two regular expressions

One of my favorite ways to print out only the lines of data between delimiters is with the range operator (..) also called the "flip-flop" op. If we drop the initial print (Items found under [moo]), this can be done with a fairly straight forward one-liner:
perl -ne'print if /^\[moo\]/../^\[cow\]/ and !/^\[/' log.log
But let's go ahead and blow this up:
use strict; use warnings; open FH, '<', 'log.log' or die "can't open file\n"; print "Items found under [moo]\n"; while (<FH>) { if (/^\[moo\]/../^\[cow\]/) { print unless /^\[/; } }
Basically, the left hand side of the .. op is the delimiter you want to start printing when found, and the right hand side of the .. op is the delimiter you want to stop printing when found. Since you don't want to print the delimiters themselves, you have to add a condition to do so. I picked anything that starts with a left bracket, you will have to pick something better if your data will start with one.

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: Re: print data between two regular expressions
by jmcnamara (Monsignor) on Oct 08, 2003 at 09:19 UTC

    For the case where it isn't known that [cow] follows [moo] you could also use the ... range operator to make the solution more general. The following prints the range from [moo] to the next line starting with [:
    perl -ne'print if /^\[moo\]/ ... /^\[/ and !/^\[/' log.txt

    The 3 dot operator ... works like the 2 dot operator .. except that the right operand isn't tested until the next evaluation.

    --
    John.

Re: print data between two regular expressions
by Abigail-II (Bishop) on Oct 08, 2003 at 11:10 UTC
    And here's a solution that doesn't depend on the presence or absense of a specific pattern in the intermediate lines of data:
    perl -ne 'print if (/^\[moo]/ and $c = 0, 1) .. (/^\[cow]/ and $c = 0, 1) and $c ++' log.log

    Abigail