I was wondering if anyone could tell me if there is a function available in unix, bash that compares all of the lines of the files. If they are different it should output true/false, or -1,0,1. I know these cmp functions exist in other languages. I have been looking around the man pages but have been unsuccessful. If it is not available, could someone help me come up with an alternative solution?
Thanks
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 thediff
command can take a parameter that tells it not to output anything. However, most don't. After all, you usediff
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 if
s:
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
来源:https://stackoverflow.com/questions/12736013/comparison-function-that-compares-two-text-files-in-unix