我正在编写一个脚本,其中我希望从一个文件中提取每一行,并检查另一个文件中的匹配项。如果我找到一个匹配项,我想说我找到了一个匹配项,如果没有,就说我没有找到匹配项。
这两个文件包含md5散列。旧文件是原始文件,而新文件将检查自原始文件以来是否有任何更改。
原文件: chksum新文件:chksum1
#!/bin/bash
while read e; do
while read f; do
if [[ $e = $f ]]
then
echo $e "is the same"
else
if [[ $e != $f]]
then
echo $e "has been changed"
fi
fi
done < chksum1
done < chksum
我的问题是,对于已更改的文件,每次循环中的检查完成时,我都会收到一个回显,我希望它只显示该文件一次,并表示没有找到该文件。
希望这一点是清楚的。
发布于 2013-06-13 20:36:49
您可以使用相同的脚本,但添加一个提醒。
#!/bin/bash
while read e; do
rem=0
while read f; do
if [[ $e = $f ]]
then
rem=1
fi
done < chksum1
if [[ rem = 1 ]]
then
echo $e "is the same"
else
echo $e "has been changed"
fi
done < chksum
这应该可以正常工作
发布于 2013-06-13 20:42:35
你们真的很亲密。这将会起作用:
while read e; do
while read f; do
found=0
if [[ $e = $f ]]
then
# echo $e "is the same"
found=1
break
fi
done < chksum1
if [ $found -ne 0 ]
then
echo "$e is the the same"
else
echo "$e has been changed"
fi
done < chksum
发布于 2013-06-13 21:07:35
一个稍微简化的版本,避免了多次读取同一文件(bash 4.0及更高版本)。我假设这些文件包含惟一的文件名,并且文件格式是md5sum命令的输出。
#!/bin/bash
declare -A hash
while read md5 file; do hash[$file]=$md5; done <chksum
while read md5 file; do
[ -z "${hash[$file]}" ] && echo "$file new file" && continue
[ ${hash[$file]} == $md5 ] && echo "$file is same" && continue
echo "$file has been changed"
done <chksum1
此脚本将第一个文件读入名为hash
的关联数组中。索引是文件名,值是MD5校验和。第二个循环读取第二个校验和文件;文件名不在hash
中,它输出file new file
;如果它在hash
中,并且值等于,则它是同一个文件;如果不等于,则写入file has been changed
。
输入文件:
$ cat chksum
eed0fc0313f790cec0695914f1847bca ./a.txt
9ee9e1fffbb3c16357bf80c6f7a27574 ./b.txt
a91a408e113adce865cba3c580add827 ./c.txt
$ cat chksum1
eed0fc0313f790cec0695914f1847bca ./a.txt
8ee9e1fffbb3c16357bf80c6f7a27574 ./b.txt
a91a408e113adce865cba3c580add827 ./d.txt
输出:
./a.txt is same
./b.txt has been changed
./d.txt new file
扩展版本
还可以检测已删除的文件。
#!/bin/bash
declare -A hash
while read md5 file; do hash[$file]=$md5; done <chksum
while read md5 file; do
[ -z "${hash[$file]}" ] && echo "$file new file" && continue
if [ ${hash[$file]} == $md5 ]; then echo "$file is same"
else echo "$file has been changed"
fi
unset hash[$file]
done <chksum1
for file in ${!hash[*]};{ echo "$file deleted file";}
输出:
./a.txt is same
./b.txt has been changed
./d.txt new file
./c.txt deleted file
https://stackoverflow.com/questions/17095899
复制