2017-03-09 87 views
0

我正在尋找一種方法來查找當前目錄以前的任何目錄是否有遞歸的任何重複目錄。
遞歸找到具有相同文件名集的目錄

/user/guy/textfile1.txt 
/user/guy/textfile2.txt 
/user/guy/textfile3.txt 
/user/girl/textfile1.txt 
/user/girl/textfile2.txt 
/user/girl/textfile3.txt 
/user/fella/textfile1.txt 
/user/fella/textfile2.txt 
/user/fella/textfile3.txt 
/user/fella/textfile4.txt 
/user/rudiger/rudy/textfile1.txt 
/user/rudiger/rudy/textfile2.txt 
/user/rudiger/rudy/textfile3.txt 
/user/julian/rudy/textfile1.txt 
/user/julian/rudy/textfile2.txt 
/user/julian/rudy/textfile3.txt 

/女孩/男孩/魯迪是重複的目錄,所以會/ Julian和呂迪格。我們還將檢查是否有任何其他文件包含與「用戶」相同的文件/目錄。當我們從「user」運行腳本作爲當前目錄時,我們想檢查當前目錄以及任何重複的行。

我當前的代碼工作...但它是非遞歸這是一個問題。

for d in */ ; do 
    for d2 in */ ; do 
    if [ "$d" != "$d2" ] ; then 
     string1="$(ls "$d2")" 
     string2="$(ls "$d")" 
     if [ "$string1" == "$string2" ] ; then 
      echo "The directories $d and $d2 are the same" 
     fi 
    fi 
    done 
done 
+0

生成的每個目錄的內容的散列值。按哈希排序該列表。兩行相鄰,具有相同的散列==兩個具有相同名稱條目的目錄。 –

+0

......你真的不想兩兩比較這種比較 - 這意味着隨着目錄數量的增長,你的指數運行時間會增加。 –

回答

2
#!/usr/bin/env bash 
#    ^^^^- must be bash, not /bin/sh, and version 4.0 or newer. 

# associative array mapping hash to first directory seen w/ same 
declare -A hashes=() 

# sha256sum requiring only openssl, vs GNU coreutils 
sha256sum() { openssl dgst -sha256 -r | sed -e '[email protected][[:space:]].*@@'; } 

while IFS= read -r -d '' dirname; do 
    hash=$(cd "$dirname" && printf '%s\0' * | sha256sum) 
    if [[ ${hashes[$hash]} ]]; then 
    echo "COLLISION: Directory $dirname has same filenames as ${hashes[$hash]}" 
    else 
    hashes[$hash]=$dirname 
    fi 
done < <(find . -type d -print0) 
相關問題