Joe Caruso
Joe Caruso

Reputation: 1394

bash script display line number from reading a file

I have a bash script that takes two files as command line input and check to see if they are the same file.

I'm trying to enhance my script so that when it determines if two files are different it also displays the line number it last read from. Is there a way to do this without just making a counter in the loop?

What I got now:

while read line1 0<&3
do
    if read line2 0<&4
        then
        # if line are different, the two files are not the same
        if [ "$line1" != "$line2" ]
            then
            echo "$1 and $2 are different"
            echo "            $1: $line1"
            echo "            $2: $line2"
            exit 1
        fi
    else
        # if EOF for file2 is reached then file1 is bigger than file2
        echo "$1 and $2 are different and $1 is bigger than $2."
        exit 1
    fi
done

It will print the containing line from the files it is checking, but not the line number right now? Any tips?

Upvotes: 1

Views: 1828

Answers (2)

mateor
mateor

Reputation: 1369

Unless you have a real reason, I would go ahead and use the existing tools. man diff will show you how to do exactly what you are attempting, but with options.

Upvotes: 0

thom
thom

Reputation: 2332

No counter ?...that is a pity because that is the most efficient way...but nevertheless, Here is a very small change to your code to make it show linenumbers without using a counter:

#!/bin/bash

exec 3< <( grep -n "" $1 )
exec 4< <( grep -n "" $2 )

while read line1 <&3
do
    if read line2 <&4
        then
        # if line are different, the two files are not the same
        if [ "$line1" != "$line2" ]
            then
            echo "$1 and $2 are different"
            echo "            $1: $line1"
            echo "            $2: $line2"
            exit 1
        fi
    else
        # if EOF for file2 is reached then file1 is bigger than file2
        echo "$1 and $2 are different and $1 is bigger than $2."
        exit 1
    fi
done

Upvotes: 2

Related Questions