Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CSV file compare

Status
Not open for further replies.

subok

MIS
Feb 21, 2005
37
BE
Hi,

I was wondering if somebody can assist creating a script.

I have 2 files

/*file1
Jagelka;12345
Vladimir;12645
Kosman;12945;
Djokivic;12347

/*file2
12345
12645
12945

Would like to have a resulting file as follow when compared

/*Result1
Jagelka;12345
Vladimir;12645
Kosman;12945

 
Try this. You can remove either line 9 or 10:

open("keyfile","<keyfile.dat");
open("datfile","<datfile.dat");

@keys = <keyfile>; # Read entire key file into an array
chop(@keys); # Strip off linefeed

@keys{@keys} = @keys; # Put keys into hash like this: $keys{'keyvalue'}=$keyvalue; Got this from a Perl book. Never understood why it works
$keys{$_} = "" foreach(@keys);# or do this instead which does: $keys{'keyvalue'}=""

while(<datfile>) {
$record=$_;
chop($record); # Strip off linefeed

($value,$key) = split(/;/, $record);

print "$record\n" if exists($keys{$key});
}
 
Not tested;

Code:
use strict;
my $path_to_keys = '';
my $path_to_file = '';

open(keys, "<$path_to_keys") or die "Can't open $path_to_keys:$!\n";;
@keys = <keys>;
chomp @keys;
close(keys);

open(file, "<$path_to_file") or die "Can't open $path_to_file:$!\n";
@file = <file>;
chomp @file;
close(file);

for my $line (@file) {
 my ($value, $key) = split(/\;/, $line);
 if (grep /$key/, @keys) {
  print "$line\n";
 }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top