2015-02-09 159 views
1

我希望能夠刪除重複的文件,同時創建一個符號鏈接去除重複行。到目前爲止,我可以顯示重複的文件,問題是刪除和刪除。因爲我要保留一個副本刪除Unix中的重複文件

find "[email protected]" -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的符號鏈接。

+0

1.爲什麼要刪除'tope1cfinal'而不是'測試/ tope1c'? 2.爲什麼你想要一個符號鏈接而不是硬鏈接? (這兩個問題有某種相關性:硬鏈接會使過程更加對稱)。 – 2015-02-09 10:26:44

+0

一個符號鏈接將指向原始文件。因爲某些程序仍然想訪問原始刪除的文件,符號鏈接就足夠了 – Alexander 2015-02-09 11:47:23

+0

這並不能解釋爲什麼您更喜歡通過硬鏈接進行符號鏈接。並且這並不回答問題1. – 2015-02-09 11:48:47

回答

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 

(未經測試,使用你自己的風險!)

+0

它正確保存爲ln -r。-r開關不存在。 – Alexander 2015-02-11 14:07:34

+0

@Alexander:這可能取決於您正在使用的「ln」版本。很高興幫助! – 2015-02-11 19:07:19