在Unix中删除重复文件

时间:2015-02-09 10:13:06

标签: bash shell

我希望能够删除重复的文件,同时创建一个指向删除的重复行的符号链接。到目前为止我可以显示重复的文件,问题是删除和删除。因为我想保留副本

find "$@" -type f -print0 | xargs -0 -n1 md5sum | sort --key=1,32 | uniq -w 
32 -d --all-repeated=separate 

输出

1463b527b1e7ed9ed8ef6aa953e9ee81  ./tope5final
1463b527b1e7ed9ed8ef6aa953e9ee81  ./Tests/tope5

2a6dfec6f96c20f2c2d47f6b07e4eb2f  ./tope3final
2a6dfec6f96c20f2c2d47f6b07e4eb2f  ./Tests/tope3

5baa4812f4a0838dbc283475feda542a  ./tope1bfinal
5baa4812f4a0838dbc283475feda542a  ./Tests/tope1b

69d7799197049b64f8675ed4500df76c  ./tope3afinal
69d7799197049b64f8675ed4500df76c  ./Tests/tope3a

945fe30c545fc0d7dc2d1cb279cf9c04  ./Tests/butter6
945fe30c545fc0d7dc2d1cb279cf9c04  ./Tests/tope6

98340fa2af27c79da7efb75ae7c01ac6  ./tope2cfinal
98340fa2af27c79da7efb75ae7c01ac6  ./Tests/tope2c

d15df73b8eaf1cd237ce96d58dc18041  ./tope1afinal
d15df73b8eaf1cd237ce96d58dc18041  ./Tests/tope1a

d5ce8f291a81c1e025d63885297d4b56  ./tope4final
d5ce8f291a81c1e025d63885297d4b56  ./Tests/tope4

ebde372904d6d2d3b73d2baf9ac16547  ./tope1cfinal
ebde372904d6d2d3b73d2baf9ac16547  ./Tests/tope1c

在这种情况下,例如我想删除./tope1cfinal并保留./Tests/tope1c。删除后我还想创建一个名称/ tope1cfinal指向/ Tests / tope1c的符号链接。

1 个答案:

答案 0 :(得分:1)

一种可能性:创建一个关联数组,其中的键是md5sum,其中的字段是找到的相应的第一个文件(不会被删除的文件)。每次在此关联数组中找到md5sum时,将删除该文件并创建相应键的相应链接(在检查要删除的文件不是原始文件之后)。将目录作为参数进行搜索;没有参数,搜索在当前目录中执行。

#!/bin/bash

shopt -s globstar nullglob

(($#==0)) && set .

declare -A md5sum=() || exit 1;
while(($#)); do
    [[ $1 ]] || continue
    for file in "$1"/**/*; do
        [[ -f $file ]] || continue
        h=$(md5sum < "$file") || continue
        read h _ <<< "$h" # This line is optional: to remove the hyphen in the md5sm
        if [[ ${md5sum[$h]} ]]; then
            # already seen this md5sum
            [[ "$file" -ef "${md5sum[$h]}" ]] && continue # prevent unwanted removal!
            rm -- "$file" || continue
            ln -rs -- "${md5sum[$h]}" "$file"
        else
            # first time seeing this file
            md5sum[$h]=$file
        fi
    done
    shift
done

(未经测试,请自担风险使用!)