http://qs321.pair.com?node_id=721864
Category: Text Processing
Author/Contact Info graff
Description: This is like the standard unix "uniq" tool to remove lines from an input stream when they match the content of the preceding line, except that the determination of matching content can be limited to specific columns of flat-table data. There's an option to keep just the first matching line or just the last matching line. Note that if the input is not sorted with respect to the column(s) of interest, non-adjacent copies will not be removed (just like with unix "uniq"). (update: note that column delimiters are specifiable by a command-line option)

The code has been updated to avoid the possible "out of memory" condition cited by repellent in the initial reply below.

#!/usr/bin/perl

use strict;
use Getopt::Long;
use Pod::Usage;

my ( $delim, $colspec, $last, $man, $help ) = ( 'default', '1', 0, 0, 
+0 );
my $argok = GetOptions( 'l' => \$last, 'c=s' => \$colspec,
                        'd=s' => \$delim, 'm' => \$man, 'h|?' => \$hel
+p );

pod2usage(-exitstatus => 0, -verbose => 2) if $man;
pod2usage(1) unless ( $argok and $colspec =~ /^\d[\d,]*$/ and !$help a
+nd
                      ( @ARGV or !-t ));

my @cols = map { $_ -1 } split( /,/, $colspec );
if ( $delim ne 'default' ) {
    my %ctrl = ( tab => "\t", dot => '\.', vb => '\|', bs => '\\\\' );
    $delim = ( exists( $ctrl{$delim} )) ? qr{$ctrl{$delim}} : qr{$deli
+m};
}

my @lastseen;
my $heldline = '';
while (<>) {
    my @tkns = ( $delim eq 'default' ) ? split : split $delim;
    my $match = 0;
    for my $i ( 0 .. $#cols ) {
        $match++ if ( $tkns[$cols[$i]] eq $lastseen[$i] );
    }
    if ( @cols == $match ) {
        $heldline = $_ if ( $last );
    }
    else {
        print $heldline;
        $heldline = $_;
        $lastseen[$_] = $tkns[$cols[$_]] for ( 0..$#cols );
    }
}
print $heldline;

=head1 NAME

col-uniq

=head1 SYNOPSIS

 col-uniq [-l] [-d delim] [-c col#[,col#...]] [sorted.list ...]

 col-uniq -m   # to print user manual

=head1 DESCRIPTION

This tool will scan through lines of text that have been sorted with
respect to one or more selected columns, and in the event that two or
more consecutive lines have the same value(s) in the selected
column(s), only one line from the matching set will be output.  All
other lines, having non-repeating values in the selected column(s),
are also printed.

This tool will only work as intended if the input has been sorted with
respect to the column(s) of interest, so a typical usage would be:

  sort [...] some.list | col-uniq [...]

By default, the first whitespace-delimited column will be taken as the
column of interest, and for every set of two or more consecutive lines
having the same value in that column, only the first line will be
printed to STDOUT (along with all the other "unique" lines).

Use the "-c col#[,...]" option to select one or more specific columns
of interest, by index number (first column on each line is "1").  For
example, in a directory where varying numbers of files are created per
day, this command line:

  ls -lt | col-uniq -c 6,7

will show only the first file created on each date.  (The "ls" options
"-lt" produce a full-detail file list, sorted by date.)

Use the "-d delim_regex" option to select something other than
whitespace as the delimiter for splitting each line into columns.
The given string is passed to the perl "split" function as a regular
expression, so a wide assortment of column separation strategies is
possible (but bear in mind that the input must be sorted on the
basis of the designated columns, in order to locate all duplicates).
Also, some "specially defined" split expressions are provided for
convenience:

  -d tab : split on tabs only (not other whitespace)
     dot : split on period characters
      vb : split on the vertical-bar (pipe) symbol "|"
      bs : split on backslash

Note that if you set the delimiter to a pattern that never occurs in
the data, the result will be to check for (and remove) consecutive
full-line duplications. (This will include sets of blank lines.)

The "-l" option can be used to preserve only the last line from each
set of matching lines (in case that is preferable to keeping only the
first).

=head1 AUTHOR

David Graff

=cut