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

时间:2018-10-09 21:12:52

标签: 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

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

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

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

2 个答案:

答案 0 :(得分:1)

如果您的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

希望这会有所帮助。

答案 1 :(得分:0)

我通过使用

使它正常工作
testdir='/home/oracle/ideatest/test/'
livedir='/home/oracle/ideatest/live/'
cd /home/oracle/bankplus/ideatest/live/
        for f in *;
                 do
                        livefile=$(md5sum "$f" | cut -d" " -f1)
        for l in "$testdir"*
                 do
                        sourcefile=$(md5sum "$l" | cut -d" " -f1)
         done
                        [[ -f $f ]] && if [ $livefile == $sourcefile ]
                 then
                         echo "$f" "Found a HASH Match Copied to live2-";
                         cp $l  /home/oracle/ideatest/live2/
                 else
                         echo "$f" "MODIFIED";
                         fi;
         done
相关问题