Today at work I had a pair of files containing account numbers, one per line, and I needed to determine which numbers were in both files, and which were in each file individually. I had a bad case of brain-lock trying to get the right output from diff, and instead wrote a quick script to give the results in the format I wanted.

The script uses a single hash whose keys are account numbers, and values determine which files the account numbers were seen in: 1 for the first file, 2 for the second, 3 for both. Here I'm using bitwise OR instead of addition in case a duplicate account number appears in the same file (a | b | b == a | b).

(Also, I wouldn't turn down a way to get similar output from diff.)

#!/usr/bin/perl -w use strict; $\ = "\n"; my %h; open FA, "file_a.txt"; for(<FA>){chomp; $h{$_} |= 1}; close FA; open FB, "file_b.txt"; for(<FB>){chomp; $h{$_} |= 2}; close FB; my @keys = sort keys %h; print"Only File a:"; for (@keys) {print if $h{$_} == 1}; print "\nOnly in File b:"; for (@keys) {print if $h{$_} == 2}; print "\nIn both files:"; for(@keys){print if $h{$_} == 3};

In reply to Bitwise OR for a custom diff that ignores dups by delirium

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.