简体   繁体   中英

Compare two files and write matching data from first file using perl

First file

FirstName:LastName:Location:Country:ID

FirstName1:LastName1:Location1:Country1:ID1

FirstName2:LastName2:Location2:Country2:ID2

FirstName3:LastName3:Location3:Country3:ID3

FirstName4:LastName4:Location4:Country4:ID4

Second file

FirstName:LastName:Location:Country:Old_ID

FirstName2:LastName2:Location2:Country2:Old_ID2

FirstName4:LastName4:Location4:Country4:Old_ID4

Have to compare first and second file and print matching rows with data from first file which is have new ID's.

Below script fetches me Old_ID's from second file and not the new ones from first file

use warnings;
use strict;

my $details  = 'file2.txt';
my $old_details = 'file1.txt';

my %names;

open my $data, '<', $details or die $!;
while (<$data>)
 {
   my ($name, @ids) = split;
   push @{ $names{$_} }, $name for @ids;
 }

open my $old_data, '<', $old_details or die $!;
while (<$old_data>) 
 {
  chomp;
 print @{ $names{$_} // [$_] }, "\n";
 }

Output:

FirstName:LastName:Location:Country:Old_ID

FirstName2:LastName2:Location2:Country2:Old_ID2

FirstName4:LastName4:Location4:Country4:Old_ID4

Expected output:

FirstName:LastName:Location:Country:ID

FirstName2:LastName2:Location2:Country2:ID2

FirstName4:LastName4:Location4:Country4:ID4

Just try this way:

use strict; # Use strict Pragma
use warnings;

my ($file1, $filecnt1, $file2, $filecnt2) = ""; #Declaring variables 

$file1 = "a1.txt"; $file2 = "b1.txt";  #Sample files

readFileinString($file1, \$filecnt1); # Reading first file
readFileinString($file2, \$filecnt2); # Reading second file

$filecnt2=~s/\:Old\_ID/\:ID/g;  # Replacing that difference content

my @firstfle = split "\n", $filecnt1;  # Move content to array variable to compare
my @secndfle = split "\n", $filecnt2;

my %firstfle = map { $_ => 1 } @firstfle; #Mapping the array into hash variable
my @scdcmp = grep { $firstfle{$_} } @secndfle;

print join "\n", @scdcmp;


#---------------> File reading
sub readFileinString
#--------------->
{
    my $File = shift;
    my $string = shift;
    open(FILE1, "<$File") or die "\nFailed Reading File: [$File]\n\tReason: $!";
    read(FILE1, $$string, -s $File, 0);
    close(FILE1);
}

#---------------> File Writing
sub writeFileinString
#--------------->
{
    my $File = shift;
    my $string = shift;
    my @cDir = split(/\\/, $File);
    my $tmp = "";
    for(my $i = 0; $i < $#cDir; $i++)
    {
        $tmp = $tmp . "$cDir[$i]\\";
        mkdir "$tmp";
    }
    if(-f $File){
        unlink($File);
    }
    open(FILE, ">$File") or die "\n\nFailed File Open for Writing: [$File]\n\nReason: $!\n";
    print FILE $$string;
    close(FILE);
}

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