in reply to Find duplicate lines from the file and write it into new file.
The seek is really over kill in this case, but would be needed if you used a checksum in place of the Digest::MD5 method.#!/usr/bin/perl use strict; use Digest::MD5; my $file = shift; my ($input, $check); open($input, $file) or die "Could not open $file: $!"; open($check, $file) or die "Could not open $file: $!"; my %hash; while (!eof($input)) { my $location = tell($input); my $line = readline($input); chomp $line; my $digest = Digest::MD5::md5($line); # $digest = length($line); if (defined(my $ll = $hash{$digest})) { my $d = 0; for my $l (@$ll) { seek($check, $l, 0); my $checkl = readline($check); chomp $checkl; if ($checkl eq $line) { print "DUP $line\n"; $d = 1; last; } } if ($d == 0) { push(@{$hash{$digest}}, $location); } } else { push(@{$hash{$digest}}, $location); } }
Note: This will only save memory if the average line length is longer than 16 bytes.
UPDATE: Changed code to correctly handle problem pointed out by Corion.
Solution for wojtyk. This will let you have up to 256 passes. It does assume that there is a random distribution of the first byte of the Digest.
#!/usr/bin/perl use strict; use Digest::MD5; my $file = shift; my ($input, $check); open($input, $file) or die "Could not open $file: $!"; open($check, $file) or die "Could not open $file: $!"; my %hash; my $passes = 2; for (my $pass = 0; $pass < $passes; $pass++) { while (!eof($input)) { my $location = tell($input); my $line = readline($input); chomp $line; my $digest = Digest::MD5::md5($line); my $p = ord($digest); if ($p % $passes != $pass) { next; } if (defined(my $ll = $hash{$digest})) { my $d = 0; for my $l (@$ll) { seek($check, $l, 0); my $checkl = readline($check); chomp $checkl; if ($checkl eq $line) { print "DUP $line\n"; $d = 1; last; } } if ($d == 0) { push(@{$hash{$digest}}, $location); } } else { push(@{$hash{$digest}}, $location); } } seek($input, 0, 0); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Find duplicate lines from the file and write it into new file.
by Corion (Patriarch) on Jan 04, 2007 at 15:58 UTC | |
|
Re^2: Find duplicate lines from the file and write it into new file.
by wojtyk (Friar) on Jan 04, 2007 at 19:15 UTC |