Here is a script to compare two files line by line. The script compares two files that are given as input on the command line and outputs only the lines that are different between the two files .
It sure is not the most optimal script, but it works :-)
For eg let us take these two files
file1:
123
456
789
file2:
123
456
432
Save the above script as compare.sh and give execute permission to the script
$ chmod +x compare.sh
Run the script as follows.
$ ./compare.sh file1 file2
output :
Differing lines are
789
432
*****************************************compare.sh*******************
#!/bin/bash
if [ $# -ne 2 ]; then
echo " Usage compare fil1 file2"
exit
fi
i=0
while read line1
do
flag=1
while read line2
do
if [ "$line1" == "$line2" ]; then
flag=0
fi
done < $2
if [ $flag -eq 1 ]; then
lines[i]=$line1
((i++))
fi
done < $1
while read line1
do
flag=1
while read line2
do
if [ "$line1" == "$line2" ]; then
flag=0
fi
done < $1
if [ $flag -eq 1 ]; then
lines[i]=$line1
((i++))
fi
done < $2
echo "Differing lines are"
for((j=0;j<i;j++))
do
echo ${lines[j]}
done
*********************************************************************
It sure is not the most optimal script, but it works :-)
For eg let us take these two files
file1:
123
456
789
file2:
123
456
432
Save the above script as compare.sh and give execute permission to the script
$ chmod +x compare.sh
Run the script as follows.
$ ./compare.sh file1 file2
output :
Differing lines are
789
432
*****************************************compare.sh*******************
#!/bin/bash
if [ $# -ne 2 ]; then
echo " Usage compare fil1 file2"
exit
fi
i=0
while read line1
do
flag=1
while read line2
do
if [ "$line1" == "$line2" ]; then
flag=0
fi
done < $2
if [ $flag -eq 1 ]; then
lines[i]=$line1
((i++))
fi
done < $1
while read line1
do
flag=1
while read line2
do
if [ "$line1" == "$line2" ]; then
flag=0
fi
done < $1
if [ $flag -eq 1 ]; then
lines[i]=$line1
((i++))
fi
done < $2
echo "Differing lines are"
for((j=0;j<i;j++))
do
echo ${lines[j]}
done
*********************************************************************
It's nice one.
ReplyDeleteCould you please let me know if it's possible to list the difference in column wise? Or just a break or new line after displaying output of file one ( like a separation)
Sample output
==============
File 1 File 2
123 345
456 456
789 888