0
votes

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
1
Please include a small example of the input file $file and what would be the expected output for that file. And then show another file that does not contain D001, and the corresponding output for that file. For example: "expected output is: $FSIZE = 5" or something like that - Håkon Hægland
Thanks for the update! What would be the expected output for the file you included? If you remove the lines with a "."? What would be the expected output if the line with D0001 was missing? - Håkon Hægland
The expected output if I remove '.' would be 3. Basically, I want to count the number of lines until the delimiter. The delimiter is "D0001" and "0000" in the following line. - Jigar Vaidya

1 Answers

2
votes

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;
            }
        }
    }
}