Comparison function that compares two text files in Unix

安稳与你 提交于 2019-12-03 10:53:29
David W.

There are several ways to do this:

  • cmp -s file1 file2: Look at the value of $?. Zero if both files match or non-zero otherwise.
  • diff file1 file2 > /dev/null: Some forms of the diff command can take a parameter that tells it not to output anything. However, most don't. After all, you use diff to see the differences between two files. Again, the exit code (you can check the value of $? will be 0 if the files match and non-zero otherwise.

You can use these command in a shell if statement:

if cmp -s file1 file2
then
   echo "The files match"
else
   echo "The files are different"
fi

The diff command is made specifically for text files. The cmp command should work with all binary files too.

There is a simple cmp file file command that does just that. It returns 0 if they are equal and 1 if they are different, so it's trivial to use in ifs:

if cmp file1 file1; then
    ...
fi

Hope this helps =)

#!/bin/bash

file1=old.txt
file2=new.txt

echo " TEST 1 : "
echo

if [ $( cmp -s ${file1} ${file2}) ]
then
   echo "The files match"
else
   echo "The files are different"
fi

echo
echo " TEST 2 : "
echo
bool=$(cmp -s "$file1" "$file2" )
if cmp -s "$file1" "$file2"
then
   echo "The files match"
else
   echo "The files are different"
fi

echo
echo " TEST 3 : "
echo

md1=$(md5 ${file1});
md2=$(md5 ${file2});

mdd1=$(echo $md1 | awk '{print $4}' ) 
mdd2=$(echo $md2 | awk '{print $4}' ) 
echo $md1
echo $mdd1
echo $md2
echo $mdd2
echo

#if [ $mdd1 = $mdd2 ]; 
if [ $mdd1 -eq $mdd2 ]; 
then
   echo "The files match"
else
   echo "The files are different"
fi

You could do an md5 on the two files, then compare the results in bash.

No Unix box here to test, but this should be right.

#!/bin/bash

md1=$(md5 file1);
md2=$(md5 file2);

if [ $md1 -eq $ $md2 ]; then
  echo The same
else
  echo Different
fi

echo "read first file" read f1 echo "read second file" read f2

diff -s f1 f2 # prints if both files are identical

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!