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};
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Bitwise OR for a custom diff that ignores dups
by toolic (Bishop) on Aug 03, 2011 at 03:06 UTC | |
by delirium (Chaplain) on Aug 03, 2011 at 13:51 UTC |