【问题标题】:Recursively find directories with identical sets of filenames递归查找具有相同文件名集的目录
【发布时间】:2017-03-09 23:27:50
【问题描述】:

我正在寻找一种方法,以递归方式查找从当前目录开始的任何目录是否有任何重复目录。

/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

/girl 和 /guy /rudy 将是重复的目录,/julian 和 rudiger 也是如此。我们还将检查是否有任何其他文件包含与“用户”相同的文件/目录。当我们从“用户”作为当前目录运行脚本时,我们还想检查当前目录是否有任何重复项。

我当前的代码可以工作......但它不是递归的,这是一个问题。

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

【问题讨论】:

  • 生成每个目录内容的哈希值。按哈希对该列表进行排序。彼此相邻的两行具有相同的哈希 == 两个具有相似名称条目的目录。
  • ...您真的不想成对地进行这种比较——这意味着随着目录数量的增长,您的运行时间呈指数增长。

标签: shell recursion directory


【解决方案1】:
#!/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 's@[[: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)

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    相关资源
    最近更新 更多