use strict; use warnings; open my $fileA, ... or die; open my $fileB, ... or die; # same with the other files my $lineB = ''; while( my $lineA = <$fileA> ) { chomp $lineA; next unless $lineA =~ m/^\d\.+(\d{2}):(\d{2}):(\d{2})\.+(\d{2})(\d{2})(\d{2})\d{2}.abc/; my $dateA = ... ; # construct date from $1, $2 etc do { chomp $lineB; next unless $lineB =~ m/^\d\.+(\d{2}):(\d{2}):(\d{2})\.+(\d{2})(\d{2})(\d{2})\d{2}.abc/; my $dateB = ... ; # construct date ... next if $dateB < $dateA; # use some date and time library for these comparisons last if $dateB > $dateA; # ... $lineA .= $lineB; } while( $lineB = <$fileB> ); # same with fileC etc... print "$lineA\n"; }