Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lines in same file

Given a file like the following:-

01/09/2005
02/09/2005
03/09/2006
03/09/2006

I wish to compare if the last two lines are the same, and return a 1 if so or a 0 if they are not.

I can get the last two using a cat tail -2

like image 948
general exception Avatar asked Oct 28 '25 03:10

general exception


2 Answers

tail -n 2 filename.txt | uniq | wc -l

This will yield 1 for identical lines, 2 for different.

like image 130
phs Avatar answered Oct 30 '25 09:10

phs


How about this:

lc=`wc -l filename.txt | cut -d " " -f1`
if [ $lc -ge 2 ]
then 
    ulc=`tail -n 2 filename.txt | uniq | wc -l`
    if [ $ulc -eq 1 ]
    then
        echo "Last two lines are identical"
    fi
fi
like image 30
jman Avatar answered Oct 30 '25 10:10

jman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!