#!/opt/gnu/bin/perl

# usage:  bibmerge bibfiles
# merges .bib files to standard output, removing duplicates.

# an array of the citations, indexed by the bib key
@cite_keys = ();

# an array of string abbreviations, indexed by the abbreviation
# (for entries such as
@abbreviations = ();

# break chunks at @ signs
$/ = '@';

while (<>) {
    chop;  # chop off the @ sign
    if (($abbr) = ($_ =~ m/\s*string\s*[\{\(]\s*(\w+)/i) ) { # if it's a string
	$abbreviations{$abbr} = $_;
    } elsif (($key) = ($_ =~ m/[^\(\{][\(\{]\s*([^,\s]*)\s*,/) ) {
	$cite_keys{$key} = $_;
    }
}

# print each unique abbreviation command
while ( ($abbr,$string) = each %abbreviations) {
    print "\@$string";
}

# print each uniquely keyed entry
while( ($key,$value) = each %cite_keys) {
    print "\@$value";
}


syntax highlighted by Code2HTML, v. 0.9.1