3

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

general exception
  • 4,202
  • 9
  • 54
  • 82

4 Answers4

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

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

phs
  • 10,687
  • 4
  • 58
  • 84
2

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
jman
  • 11,334
  • 5
  • 39
  • 61
2

Try this

[ `cat | tail -n 2 | uniq | wc -l` -eq "1" ] && echo 1 || echo 0

Replace echo by exit to make it the exit value. Used echo just for quicker testing.

#!/bin/bash
[ `cat | tail -n 2 | uniq | wc -l` -eq "1" ] && exit 1
exit 0
Daniel Böhmer
  • 14,463
  • 5
  • 36
  • 46
1

This might work for you:

 sed -n '$!h;${G;/\(.*\)\n\1$/{s/.*/1/p;q};s/.*/0/p}' filename.txt
potong
  • 55,640
  • 6
  • 51
  • 83