【问题标题】:Comparing file names and md5sums of multiple files in Linux比较Linux中多个文件的文件名和md5sums
【发布时间】:2023-03-11 13:53:01
【问题描述】:

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

到目前为止,我有这个:

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

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

  • 一些图像具有相同的名称,但不同。在这个 在这种情况下,只需将第二个“.JPG”添加到 他们名字的结尾。
  • 但是,如果两个文件具有相同的名称并且是相同的文件, 只有一个应该复制到输出目录,并且绝对 另一个路径应写入文本文件 - duplicates.txt。

我在想我需要在文件名上使用 cmp 然后 md5sum 来检查相同的文件,但我不确定如何在文件名上使用 cmp,或者这是否可能。

提前感谢您的帮助!

【问题讨论】:

  • fdupes 命令可能会做你想做的事。
  • cmp 告诉你文件是否相同,它会逐字节比较。

标签: linux bash shell md5sum cmp


【解决方案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)

【讨论】:

  • 嘿,抱歉,过了一段时间才回复您...我已经尝试运行您的代码,但它给了我 3 个错误。显然“:在第 4 行找不到命令”(可能是因为没有第 4 行)和第 22 行的 2 个错误,与语法有关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2015-04-12
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2012-05-31
相关资源
最近更新 更多