Update: After talking with ImpalaSS, modified code to handle multiple entries in the first file with the same matching key.


Quick solution. Not the best way, as it is not very flexible, but gets the job done. Requires the two files to be joined as the first and second arguemnts, and the file to be created as the third. Outputs any "unmached" records.

#!/dev/null/perl -- :) use strict; my $first = shift or die "Need the first file!\n"; my $second = shift or die "Need the second file!\n"; my $third = shift or die "Need the third file!\n"; ## May as well test them all now open(FIRST, "$first") or die "Could not open $first: $!\n"; open(SECOND, "$second") or die "Could not open $second: $!\n"; open(THIRD, ">$third") or die "Could not write $third: $!\n"; my (%first, %found); while(<FIRST>) { my ($key, @cols) = split(m#\|# => $_, -1); push(@{$first{$key}}, \@cols); $found{$key} = $.; } close(FIRST); while(<SECOND>) { my ($one, $key, @cols) = split(m#\|# => $_, -1); if (exists $first{$key}) { delete $found{$key}; for (@{$first{$key}}) { print THIRD "$_->[0]|$one|$cols[0]\n"; } } else { printf "Line %5d: Record %5d exists in $second but not in $first\n +", $.,$key; } } close(SECOND); close(THIRD); ## Double check the first file: for (sort {$found{$a} <=> $found{$b}} keys %found) { printf "Line %5d: Record %5d exists in $first but not in $second\n", $found{$_},$_; }

In reply to Re: Combining Files by turnstep
in thread Combining Files by ImpalaSS

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.