比较文件夹与文件夹结构

比较文件夹与文件夹结构

我有相机的 SD 卡,里面有照片和胶片。在我的主盒子上,我有一个文件夹结构,目录名称如下:images/YYYY-MM-description,有时下面有不同名称的子文件夹。 SD 卡上的文件名与文件夹中的文件名相同。

我想将 SD 卡与文件夹结构进行比较(校验和),以查明我的盒子是否包含 SD 卡上的所有文件。我想过对它们进行 MD5 处理,但任何适合用例的算法都可以。

我想过使用rsyncor diff,但由于我的盒子上有多层结构,我无法想出解决方案。

系统是 Debian 的,以防万一。

答案1

您可以使用 md5deep。

sudo apt-get install md5deep

首先保存一个文件夹的结果:

md5deep -r -s /dir1> dir1sums

现在将它们与其他文件夹进行比较:

md5deep -r -X dir1sums /dir2

如果没有输出,则意味着目录是相同的。否则,它将显示不同文件的哈希值。

答案2

我将做以下假设:

1)所有文件名都是唯一的

2)您只想检查丢失的文件(如果每个设备上的文件具有相同的 md5 和,即图片是否损坏)

3)文件只能在本机缺失,SD卡默认有所有文件

除了假设 1 之外,还可以更改脚本以在任一位置查找单个文件,甚至对每个文件对进行 md5 交叉检查。

这样,我们可以使用,选择所有文件名并检查ue 文件名find列表uniq

#!/bin/bash

#load all file names from local dir as array:
pics_local=( $( find /path/to/dir/ -type f -printf "%f\n" ) )
#load all file names from SD card as array:
pics_SD=( $( find /mnt/SD/ -type f -printf "%f\n" ) )
#see if files are only in one of them,
#i.e. if file names appear only once (save as array):
singulars=( $( printf "%s\n" ${pics_local[@]} ${pics_SD[@]} |\
            sort | uniq -u ) )
#print list of missing files with full paths using find:
for (( i=0 ; i<=${#singulars[@]}-1 ; i++ )) ; do
    find /mnt/SD/ -type f -name "${singulars[$i]}"
done

更新:每个文件带有 md5sum 的脚本:我们在 SD 上拥有所有文件,并在本地目录中搜索丢失的文件。所有本地文件与SD文件相同(没有md5和不匹配的对应文件)

#!/bin/bash

#load file names and md5sums of files on SD card into array
files_SD=( $( find /mnt/SD/ -type f ) )
md5_SD=( $( find /mnt/SD/ -type f -exec md5sum {} + | cut -d' ' -f1 ) )
#load md5sums of files in local folder into array:
md5_loc=( $( find /local/dir/ -type f -exec md5sum {} + | cut -d' ' -f1 ) )

#check for the very unlikely possibility of md5sums
#matching for more than two files
#IMHO: can be safely skipped
if [[ $(sort <( printf '%s\n' ${md5_loc[@]} ${md5_SD[@]}) |\
      uniq -c | awk ' $1 >= 3 ' ) ]] ; then
  echo "md5 sums matching for more than 2 files!"
  echo "critical error, aborting"
  exit
fi

singular_md5s=( $( printf '%s\n' ${md5_loc[@]} ${md5_SD[@]} | sort | uniq -u ) )
for (( i=0 ; i<=${#singular_md5[@]}-1 ; i++ )) ; do
  #assume SD card has all files
  #print file that is missing in local folder:
  #1) find where it is in the array:
  n=$(( $(grep -n "${singular_md5s[$i]}" <( printf '%s\n' ${md5_SD[@]} ) | cut -d: -f1 )-1 ))
  #2) print file name
  echo "${files_SD[$n]} missing on local folder"
done

相关内容