简体   繁体   中英

Perl : match multiple lines

With the use of perl regex, if two consecutive lines match than count the number of lines.

I want the number of lines until matches the pattern

D001
0000
open ($file, "$file") || die; 
   my @lines_f = $file;
   my $total_size = $#lines_f +1;

   foreach my $line (@lines_f)
   {
       if ($line =~ /D001/) {
           $FSIZE = $k + 1;
       } else { 
           $k++;}
    }  

Instead of just D001, I also want to check if the next line is 0000. If so $FSIZE is the $file size. The $file would look something like this

00001 
00002
.
.
.
D0001
00000
00000

Here is an example. This sets $FSIZE to undef if it cannot find the marker lines:

use strict;
use warnings;

my $fn = 'test.txt';
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
chomp (my @lines = <$fh>);
close $fh;

my $FSIZE = undef;
for my $i (0..$#lines) {
    if ($lines[$i] =~ /D0001/) {
        if ( $i < $#lines ) {
            if ( $lines[$i+1] =~ /00000/ ) {
                $FSIZE = $i + 1;
                last;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM