CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Compare two files and merge the matched outputs.

 



tux
New User

Nov 4, 2008, 7:13 PM

Post #1 of 3 (738 views)
Compare two files and merge the matched outputs. Can't Post

Hi Gurus,

Basically i am try to read two different files and if the first element and second element match's of both files and
then print the third element values of both files to merge.txt and not matched file1.txt to not-merge.txt

file1.txt
230 234 A_1
450 769 B_1
100 300 C_1
699 342 D_1

file2.txt
450 770 B_2
230 234 A_2
699 341 D_2
100 300 C_2

Required outputs
merge.txt

A_1 = A_2
C_1 = C_2


not-merge.txt

450 769 B_1
699 342 D_1


Here is my code
#! /usr/bin/perl
open (IN1, "file1.txt");
open (IN2, "file2.txt");
open (MERGE, ">merge.txt");
open (NOT_MERGE, ">not-merge.txt");
foreach $line (<IN1>) {
chomp ($line);
($element1, $element2, $element3) = split (' ',$line);
while (<IN2>) {
@lines2 = split ;
if ($element1 eq $lines2[0] && $element2 eq $lines2[1]) {
print MERGE "$element3 = $lines2[2]\n"
}
if ($element1 ne $lines2[0] && $element2 eq $lines2[1]) {
print NOT_MERGE "file1.txt: $line\n" ;
}
}
}
close(IN1);
close(IN2);
close(MERGE);
close(NOT_MERGE);

i am getting the following output's

merge.txt
A_1 = A_2

not-merge.txt
empty

can any one help me out in looping ..

thanks
tux


travs69
Novice

Nov 4, 2008, 8:37 PM

Post #2 of 3 (728 views)
Re: [tux] Compare two files and merge the matched outputs. [In reply to] Can't Post

You need to change to a for loop on the second file instead of a while loop or your going to end up at the end of the file and never be able to go back to the beginning and check.

I think anyway.. :) if I'm wrong Kevin will correct me. I think I would push all this into a hash then compare it.. but it depends on the size of the data.


KevinR
Veteran


Nov 4, 2008, 9:42 PM

Post #3 of 3 (726 views)
Re: [travs69] Compare two files and merge the matched outputs. [In reply to] Can't Post

he can use seek() to go back to the beginning of the file.

Using a hash is a good suggestion as long as the files aren't too big.
-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives