linux - 为目录中的所有文件生成MD5sum,并在另一个目录中获取它们的匹配项

标签 linux bash md5sum

我有 2 个目录。 livedir 包含 2000 个 fmx 文件,testdir 包含 6000 个带有时间戳的 fmb。我将 testdir 中的所有 fmb 编译为 fmx,以将它们与 livedir 中的 fmx 匹配。

我创建了以下脚本来获取 livedir 中所有文件的 MD5SUM 并搜索它们是否存在于 testdir 中:

testdir='/home/oracle/ideatest/test/'
livedir='/home/oracle/ideatest/live/'
cd /home/oracle/ideatest/live/

for f in *; do
    livefile=$(md5sum "$f" | cut -d" " -f1)
    sourcefile=$(md5sum "$testdir""$f" | cut -d" " -f1)
    if [[ -f $f ]] && [ $livefile == $sourcefile ]; then
        echo "$f" "OK-----------------------------"
        echo "$sourcefilename"
        cp /home/oracle/bankplus/ideatest/test/$f  /home/oracle/bankplus/ideatest/live2/$f
        #el moshkla f 2sm el file 3ayzo mn 3'er hash
    else
        echo "$f" "MODIFIED"
    fi
done

该脚本仅在 2 个目录中存在同名文件时才起作用。这是因为我循环使用相同的名称 $f:

sourcefile=$(md5sum "$testdir""$f" | cut -d" " -f1)

结果 cp 只复制一个文件,尽管我在 testdir 中有多个具有相同哈希值的文件。

最佳答案

如果您的 bash 版本是 4.2 或更高版本,如何使用关联数组:

#!/bin/bash

testdir="/home/oracle/ideatest/test"
livedir="/home/oracle/ideatest/live"

declare -A hash

# 1st step: create a hash table of md5sum in $testdir
for f in $(find "$testdir" -type f); do
    md5sum=$(md5sum "$f" | cut -d" " -f1)
    hash[$md5sum]=${f##*/}  # holds md5sum as a key and filename as a value
done

# 2nd step: loop over files in $livedir and test if md5sum value of a file
# exists in $testdir
for f in $(find "$livedir" -type f); do
    basename=${f##*/}
    md5sum=$(md5sum "$f" | cut -d" " -f1)
    if [[ -n "${hash[$md5sum]}" ]]; then
        echo "$basename" "OK-----------------------------"
        echo "${hash[$md5sum]}"
        cp "/home/oracle/bankplus/ideatest/test/$basename" "/home/oracle/bankplus/ideatest/live2/$basename"
    else
        echo "$basename" "MODIFIED"
    fi
done

希望这对您有所帮助。

关于linux - 为目录中的所有文件生成MD5sum,并在另一个目录中获取它们的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52729411/

相关文章:

linux - 如何以编程方式检查依赖库的程序是否可以在Linux系统中运行?

linux - Windows CMD命令对应linux命令

JAVA Md5 返回非确定性结果

bash - 并行检查 md5 文件

c -/usr/include linux 中新建 .h 文件

linux - 增加根分区大小

c++ - 在 C/C++ 中使用 popen() 是一种糟糕的编码习惯吗?

linux - 在linux中使用文件作为参数运行脚本

bash - 如何设置 ffmpeg 队列?

c - 相同文件内容的不同 md5sum?