in reply to Re^3: how to change this code into perl
in thread how to change this code into perl

Thank you very much Laurent_R, I tried the script and its printing all the rows, instead of duplicates. Laurent_R, this code looks very interesting, can you please explain it

#!/usr/bin/perl my ($previous_key, $previous_line); open my $IN, "<", '/home/scripts/imageoutcome.txt' or die "cannot open + $infile $!"; while (<$IN>) { my $key = $1 if /^(\w+)/; if ($key eq $previous_key) { print $previous_line if defined $previous_line; print $_; undef $previous_line; } else { $previous_line = $_; } $previous_key = $key; }

Replies are listed 'Best First'.
Re^5: how to change this code into perl
by Laurent_R (Canon) on Aug 31, 2015 at 10:47 UTC
    I tried the script and its printing all the rows
    Then you have to show me your input data. I've just tried that script with the following input data:
    aa blah bb blah bb blahblah bb foo cc dlqskjf cc cfkqs dd dkls ee dsjkqjs ff blah gg klsqdj gg sqkl
    and it print only the lines where the first column is a duplicate, as shown in this output:
    bb blah bb blahblah bb foo cc dlqskjf cc cfkqs gg klsqdj gg sqkl
    This seems to work perfectly.

    Otherwise, the way it works is that it reads the file one line at a time, and store this line ($previous_line), as well as the comparison key until the next line is read. If they have the same key, then I print the previous line (if defined) and the current one; in such case, I undef the previous line to prevent it from being printed twice if there are triplicates.

    If it does not work properly for you, please show your input and/or test data.