比较Linux中多个文件的文件名和md5sums

时间:2015-11-19 16:59:56

标签: linux bash shell md5sum cmp

我正在编写一个bash脚本,用于将目录(及其所有子目录)中的图像复制到另一个目录。

到目前为止,我有这个:

find . -type f -regextype posix-extended -regex '^.*IMG_[0-9]{4}\.jpg' -exec cp {} ~/$output \;

这样可行,但问题比这更复杂。有两种情况:

  • 有些图片名称相同,但不同。在这 如果只是通过添加第二个“.JPG”来重命名它们 他们的名字结束。
  • 但是,如果两个文件具有相同的名称且文件相同, 只有一个应该被复制到输出目录,而绝对 另一个的路径应写入文本文件 - duplicates.txt。

我认为我需要在文件名上使用cmp然后使用md5sum来检查相同的文件,但我不确定如何在文件名上使用cmp,或者甚至可以使用cmp。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这还没有经过全面测试,但这样做对你有用吗?基本上只是围绕find的输出循环,检查您指定的条件,并执行相应的操作。输入目录作为第一个参数传递,输出为第二个参数。

#!/bin/bash

input=$1
output=$2
logfile=~/duplicates.txt

while IFS= read -r -d '' f
do
    #strip the input directory name from the file
    f=${f/$input\//}
    echo Working with $f
    #check if the file exists
    if [ -f "$output/$f" ]; then
        if cmp -s "$input/$f" "$output/$f"; then
            #file is identical
            echo "$f" >> "$logfile"
        else
            #same filename, but different file
            cp --parents -p "$input/$f" "$output/$f.JPG"
        fi
    else
        cp --parents -p "$input/$f" "$output/$f"
    fi
done< <(find "$input" -type f -regextype posix-extended -regex '^.*IMG_[0-9]{4}\.jpg' -print0)