Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Bitwise OR for a custom diff that ignores dups

by delirium (Chaplain)
on Aug 03, 2011 at 02:00 UTC ( [id://918163]=CUFP: print w/replies, xml ) Need Help??

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
    It sounds like you want comm and sort instead of diff.
      Toolic, that's exactly what I wanted; thanks.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://918163]
Approved by strredwolf
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-25 21:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found