-
Notifications
You must be signed in to change notification settings - Fork 34
/
similar_files_levenshtein.pl
executable file
·131 lines (100 loc) · 2.89 KB
/
similar_files_levenshtein.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/perl
# Author: Trizen
# Date: 13 January 2016
# https://github.com/trizen
# Finds files which have almost the same content, using the Levenshtein distance.
#
## WARNING! For strict duplicates, use the 'fdf' script:
# https://github.com/trizen/perl-scripts/blob/master/Finders/fdf
#
use 5.010;
use strict;
use warnings;
use Fcntl qw(O_RDONLY);
use File::Find qw(find);
use Getopt::Long qw(GetOptions);
use Text::LevenshteinXS qw(distance);
use Number::Bytes::Human qw(parse_bytes);
my $unique = 0;
my $threshold = 70;
my $max_size = '100KB';
sub help {
my ($code) = @_;
print <<"HELP";
usage: $0 [options] [/dir/a] [/dir/b] [...]
options:
-s --size=s : maximum file size (default: $max_size)
-u --unique! : don't include a file in more groups (default: false)
-t --threshold=f : threshold percentage (default: $threshold)
Example:
perl $0 ~/Documents
HELP
exit($code // 0);
}
GetOptions(
's|size=s' => \$max_size,
'u|unique!' => \$unique,
't|threshold=f' => \$threshold,
'h|help' => \&help,
)
or die("Error in command line arguments");
@ARGV || help();
$max_size = parse_bytes($max_size);
sub look_similar {
my ($f1, $f2) = @_;
sysopen my $fh1, $f1, O_RDONLY or return;
sysopen my $fh2, $f2, O_RDONLY or return;
my $s1 = (-s $f1) || (-s $fh1);
my $s2 = (-s $f2) || (-s $fh2);
my ($min, $max) = $s1 < $s2 ? ($s1, $s2) : ($s2, $s1);
my $diff = int($max * (100 - $threshold) / 100);
($max - $min) > $diff and return;
sysread($fh1, (my $c1), $s1) || return;
sysread($fh2, (my $c2), $s2) || return;
distance($c1, $c2) <= $diff;
}
sub find_similar_files (&@) {
my $code = shift;
my %files;
find {
no_chdir => 1,
wanted => sub {
lstat;
(-f _) && (not -l _) && do {
my $size = -s _;
if ($size <= $max_size) {
# TODO: better grouping
push @{$files{int log $size}}, $File::Find::name;
}
};
}
} => @_;
foreach my $key (sort { $a <=> $b } keys %files) {
next if $#{$files{$key}} < 1;
my @files = @{$files{$key}};
my %dups;
foreach my $i (0 .. $#files - 1) {
for (my $j = $i + 1 ; $j <= $#files ; $j++) {
if (look_similar($files[$i], $files[$j])) {
push @{$dups{$files[$i]}},
(
$unique
? splice(@files, $j--, 1)
: $files[$j]
);
}
}
}
while (my ($fparent, $fdups) = each %dups) {
$code->(sort $fparent, @{$fdups});
}
}
return 1;
}
{
local $, = "\n";
find_similar_files {
say @_, "-" x 80 if @_;
}
@ARGV;
}