Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking equality of a part of two files

Tags:

linux

bash

diff

Is it possible to check if first line of two files is equal using diff(or another easy bash command)?

[Generally checking equality of first/last k lines, or even lines i to j]

like image 640
a-z Avatar asked May 03 '12 08:05

a-z


People also ask

How can you tell if two files are equal?

Comparison Using cmp GNU cmp compares two files byte by byte and prints the location of the first difference. We can pass the -s flag to find out if the files have the same content. Since the contents of file1 and file2 are different, cmp exited with status 1.

How do I compare files side by side?

Open both of the files that you want to compare. On the View tab, in the Window group, click View Side by Side. in the Window group on the View tab. If you don't see Synchronous Scrolling, click Window on the View tab, and then click Synchronous Scrolling.

How do I compare the contents of two files in Windows?

On the File menu, click Compare Files. In the Select First File dialog box, locate and then click a file name for the first file in the comparison, and then click Open. In the Select Second File dialog box, locate and then click a file name for the second file in the comparison, and then click Open.


2 Answers

To diff the first k lines of two files:

$ diff <(head -k file1) <(head -k file2)

Similary, to diff the last k lines:

$ diff <(tail -k file1) <(tail -k file2)

To diff lines i to j:

diff <(sed -n 'i,jp' file1) <(sed -n 'i,jp' file2)
like image 162
dogbane Avatar answered Sep 28 '22 01:09

dogbane


My solution seems rather basic and beginner when compared to dogbane's above, but here it is all the same!

echo "Comparing the first line from file $1 and $2 to see if they are the same."

FILE1=`head -n 1 $1`
FILE2=`head -n 1 $2`

echo $FILE1 > tempfile1.txt
echo $FILE2 > tempfile2.txt

if diff "tempfile1.txt" "tempfile2.txt"; then
    echo Success
else
    echo Fail
fi
like image 34
David K Avatar answered Sep 28 '22 02:09

David K