in reply to Need to have perl script to compare two txt files and print difference along with under which segment the difference is

#!/usr/bin/perl # https://perlmonks.org/?node_id=1228906 use strict; use warnings; @ARGV or @ARGV = qw( tst1 tst2 ); # FIXME for testing only @ARGV == 2 or die "usage: $0 filename1 filename2\n"; my %lines; for my $file ( @ARGV ) { my $segment; open my $fh, '<', $file or die "$! opening $file"; while( <$fh> ) { if( /^\w/ ) { $segment = $_; } elsif( $segment && /\w/ ) { $lines{"$segment$_" } .= "\t$file"; } } close $fh; } my $segment; for( sort grep $lines{$_} =~ tr/\t// == 1, keys %lines ) { if( $segment && /^\Q$segment\E(.+)/ ) { print "$1$lines{$_}\n"; } elsif( /^(.*\n)/ ) { $segment = $1; print s/(?=\n$)/$lines{$_}/r; } }

Outputs:

lodv EJHFG tst1 sdmd IJFH tst2 LAKJSK tst2
  • Comment on Re: Need to have perl script to compare two txt files and print difference along with under which segment the difference is
  • Select or Download Code