Take the 2-minute tour ×

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]

share|improve this question
add comment

4 Answers

up vote 7 down vote accepted

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)
share|improve this answer
What does p mean in 'i,jp'? –  a-z May 3 '12 at 8:59
p means print. –  dogbane May 3 '12 at 9:13
and to check equality: if diff ...; then echo "equal"; else echo "not equal"; fi –  glenn jackman May 3 '12 at 10:12
add comment

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
    echo Fail
share|improve this answer
add comment

My solution uses the filterdiff program of the patchutils program collection. The following command shows the difference between file1 and file2 from line number j to k:

diff -U 0 file1 file2 | filterdiff --lines j-k
share|improve this answer
add comment

below command displays the first line of both the files.

krithika.450> head -1 temp1.txt temp4.txt
==> temp1.txt <==
Starting CXC <...> R5x BCMBIN (c)  AB 2012

==> temp4.txt <==

Below command displays yes if the first line in both the filesare equal.

krithika.451> head -1 temp4.txt temp1.txt | awk '{if(NR==2)p=$0;if(NR==5){q=$0;if(p==q)print "yes"}}'
share|improve this answer
add comment

Your Answer


