Hi Prashant,

> Can you please help me to grep below 'block of text' from my file ? this 
> blocks occurs number of time & I want to grep all in between lines of this 
> block -

There are several ways you can do this. Let’s say that “begin” is the start of 
a block, and “end” is the end. So here’s some input:

apple
orange
begin
blue
red
end
pineapple
cherry
begin
pink
yellow
end
pear
plum

You can pull out the blocks using a regular expression. For example:

use File::Slurper qw/ read_text /;
my $text = read_text($ARGV[0]);

my @blocks = $text =~ m/^begin$(.*?)^end$/msg;

Now the array @blocks has strings with the text from each of the blocks. You 
might want to trim leading and trailing newlines.

If the files are huge, or if you might want to do other processing, then you 
could try a line oriented approach:

my $in_block = 0;
my @blocks;

while (<>) {
    if (/^begin$/) {
        die "begin inside block!\n" if $in_block;
        $in_block = 1;
        push(@blocks, '');
        next;
    }
    if (/^end$/) {
        die "end outside of a block!\n" unless $in_block;
        $in_block = 0;
        next;
    }
    $blocks[-1] .= $_ if $in_block;
}

Cheers,
Neil


Reply via email to