http://www.perlmonks.org?node_id=995546


in reply to Need help for extracting Log file using Perl script

Hi!

Look at this. Probably it helps to find the way.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $filename1 = 'file1.txt'; my $filename2 = 'file2.txt'; open my $fhin1, "<", $filename1 or die "ERROR: Can't open file '$filen +ame1': $!"; open my $fhin2, "<", $filename2 or die "ERROR: Can't open file '$filen +ame2': $!"; my %lines_found_in_file1 = map { chomp; s/^\s+//; s/\s+$//; $_ => 1 } (<$fhin1>); my %lines_found_in_file2 = map { chomp; s/^\s+//; s/\s+$//; $_ => 1 } (<$fhin2>); close $fhin1 or die "ERROR: Couldn't close file '$filename1': $!"; close $fhin2 or die "ERROR: Couldn't close file '$filename2': $!"; my $output1 = 'common.txt'; my $output2 = 'uncommon.txt'; open my $fhout1, ">", $output1 or die "ERROR: Can't open file '$output +1': $!"; open my $fhout2, ">", $output2 or die "ERROR: Can't open file '$output +2': $!"; # Compare in one direction foreach my $line (keys %lines_found_in_file1) { if(exists $lines_found_in_file2{$line}) { print $fhout1 $line, "\n"; } else { print $fhout2 $line, "\n"; } } # Compare in other direction foreach my $line (keys %lines_found_in_file2) { if(exists $lines_found_in_file1{$line}) { # Don't do anything as you printed these lines in the first go } else { print $fhout2 $line, "\n"; } } close $fhout1 or die "ERROR: Couldn't close file '$output1': $!"; close $fhout2 or die "ERROR: Couldn't close file '$output2': $!";

Best regards
McA