这是对 这个问题 的一种跟进。
如果有多个 blob 具有相同的内容,则它们仅在 git 存储库中存储一次,因为它们的 SHA-1 值将是相同的。如何查找给定树中的所有重复文件?
你需要遍历整个树并寻找重复的哈希值,还是 Git 提供了从每个 blob 到引用它的树中所有文件的反向链接?
[alias]
# find duplicate files from root
alldupes = !"git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40"
# find duplicate files from the current folder (can also be root)
dupes = !"cd `pwd`/$GIT_PREFIX && git ls-tree -r HEAD | cut -c 13- | sort | uniq -D -w 40"
在我工作的代码库上运行这个程序,让我大开眼界!
#!/usr/bin/perl
# usage: git ls-tree -r HEAD | $PROGRAM_NAME
use strict;
use warnings;
my $sha1_path = {};
while (my $line = <STDIN>) {
chomp $line;
if ($line =~ m{ \A \d+ \s+ \w+ \s+ (\w+) \s+ (\S+) \z }xms) {
my $sha1 = $1;
my $path = $2;
push @{$sha1_path->{$sha1}}, $path;
}
}
foreach my $sha1 (keys %$sha1_path) {
if (scalar @{$sha1_path->{$sha1}} > 1) {
foreach my $path (@{$sha1_path->{$sha1}}) {
print "$sha1 $path\n";
}
print '-' x 40, "\n";
}
}
我刚刚写了一行代码,可以突出显示由git ls-tree
渲染的重复项。
可能会有用。
git ls-tree -r HEAD |
sort -t ' ' -k 3 |
perl -ne '$1 && / $1\t/ && print "\e[0;31m" ; / ([0-9a-f]{40})\t/; print "$_\e[0m"'
这里的脚本答案与您链接问题中的基本相同。
请尝试从您的git存储库根目录运行以下git命令。
git ls-tree -r HEAD
针对Windows/PowerShell用户:
git ls-tree -r HEAD | group { $_ -replace '.{12}(.{40}).*', '$1' } | ? { $_.Count -gt 1 } | select -expand Group
这将输出类似于:
100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename1
100644 blob 8a49bcbae578c405ba2596c06f46fabbbc331c64 filename2
100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename3
100644 blob c1720b20bb3ad5761c1afb6a3113fbc2ba94994e filename4
( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) ; done ) |sort |uniq -c |grep -vE '^\s*1\b' |sed 's/.* //' > ~/dup.md5 ; \
( for f in `find .`; do test -f $f && echo $(wc -c <$f) $(md5 -q $f) $f; done ) |fgrep -f ~/dup.md5 |sort
find -type f
和du
;您当前的版本非常低效(多次遍历文件)。我没有给你点踩,因为我猜这可能有用。 - remram
uniq
命令使用略有不同的参数,具体而言,-D
改为了-d
,-w
改为了-s
。请参阅此处的 manpage https://www.unix.com/man-page/bsd/1/UNIQ/。 - Devy