Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: move the line if particular column is duplicate or more than 1 entries

by Laurent_R (Canon)
on Mar 17, 2013 at 21:49 UTC ( #1023941=note: print w/replies, xml ) Need Help??

in reply to move the line if particular column is duplicate or more than 1 entries

To remove duplicates, just store second and third fields in a hash (as a key) when you read the line. Then, print in file 1 or in file 2 depending on whether the key already exists in the hash.

Something like this (untested):

my %already_seen; while (<>) { my @temp = split /\s\, $_; my $key = $temp[1,2]; if defined ($already_seen{$key} { # it is a duplicate print $output2 $_; } else { $already_seen{$key} = 1; print $output2 $_; } }
Code could be made more concise and the @temp array could be avoided for example with such a syntax:

$key = join " ", (split / /, $_) [1,2];

but I preferred to do it simpler to understand.

Note that this will not work if your input file is huge to the point of getting your hash too large for your memory. The limit will depend on your system, but in general, everything below a million lines should probably work without problem on most current systems. If your file is larger (especially if it is much larger), you might need a different way of doing it.

Similarly, for the order of the 6th column, just store its value in a variable when you read a line and compare 6th column with the variable (i.e. 6th column of previous line).

I leave it to you to put the two rules together.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1023941]
NodeReaper hides the Vote Fairy's wand

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (10)
As of 2018-06-22 15:55 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.