检查文件内容是否相同
check the content of the files if they are same
我有很多.txt文件(即1.txt,2.txt 3.txt ...等)保存在一个目录中,我想检查里面的文件内容目录是否相同
所有文件都应该与其他文件进行比较,如果内容相同则打印是,如果内容不同则打印否
例如:
1.txt
a
b
c
2.txt
a
b
c
3.txt
1
2
3
expected output when compare two file 1.txt 2.txt
1.txt 2.txt yes
expected output when compare two file 1.txt 3.txt
1.txt 3.txt no
expected output when compare two file 2.txt 3.txt
2.txt 3.txt no
我试过脚本
#!/bin/sh
for file in /home/nir/dat/*.txt
do
echo $file
diff $file $file+1
done
但这里的问题是它没有给出 output.Please 建议更好的解决方案,谢谢。
bash 中的类似内容:
for i in *
do
for j in *
do
if [[ "$i" < "$j" ]]
then
if cmp -s "$i" "$j"
then
echo $i $j equal
else
echo $i $j differ
fi
fi
done
done
输出:
1.txt 2.txt equal
1.txt 3.txt differ
2.txt 3.txt differ
使用文件名数组并借用 jamesbrown 的 cmp
解决方案的一个想法:
# load list of files into array flist[]
flist=(*)
# iterate through all combinations; '${#flist[@]}' ==> number of elements in array
for ((i=0; i<${#flist[@]}; i++))
do
for ((j=i+1; j<${#flist[@]}; j++))
do
# default status = "no" (ie, are files the same?)
status=no
# if files are different this generates a return code of 1 (aka true),
# so the follow-on assignment (status=yes) is executed
cmp -s "${flist[${i}]}" "${flist[${j}]}" && status=yes
echo "${flist[${i}]} ${flist[${j}]} ${status}"
done
done
对于问题中列出的 3 个文件,这会生成:
1.txt 2.txt yes
1.txt 3.txt no
2.txt 3.txt no
我有很多.txt文件(即1.txt,2.txt 3.txt ...等)保存在一个目录中,我想检查里面的文件内容目录是否相同
所有文件都应该与其他文件进行比较,如果内容相同则打印是,如果内容不同则打印否
例如: 1.txt
a
b
c
2.txt
a
b
c
3.txt
1
2
3
expected output when compare two file 1.txt 2.txt
1.txt 2.txt yes
expected output when compare two file 1.txt 3.txt
1.txt 3.txt no
expected output when compare two file 2.txt 3.txt
2.txt 3.txt no
我试过脚本
#!/bin/sh
for file in /home/nir/dat/*.txt
do
echo $file
diff $file $file+1
done
但这里的问题是它没有给出 output.Please 建议更好的解决方案,谢谢。
bash 中的类似内容:
for i in *
do
for j in *
do
if [[ "$i" < "$j" ]]
then
if cmp -s "$i" "$j"
then
echo $i $j equal
else
echo $i $j differ
fi
fi
done
done
输出:
1.txt 2.txt equal
1.txt 3.txt differ
2.txt 3.txt differ
使用文件名数组并借用 jamesbrown 的 cmp
解决方案的一个想法:
# load list of files into array flist[]
flist=(*)
# iterate through all combinations; '${#flist[@]}' ==> number of elements in array
for ((i=0; i<${#flist[@]}; i++))
do
for ((j=i+1; j<${#flist[@]}; j++))
do
# default status = "no" (ie, are files the same?)
status=no
# if files are different this generates a return code of 1 (aka true),
# so the follow-on assignment (status=yes) is executed
cmp -s "${flist[${i}]}" "${flist[${j}]}" && status=yes
echo "${flist[${i}]} ${flist[${j}]} ${status}"
done
done
对于问题中列出的 3 个文件,这会生成:
1.txt 2.txt yes
1.txt 3.txt no
2.txt 3.txt no