dbain
dbain

Reputation: 71

Values based comparison in Unix

I have two variables like below .

a=rw,bg,hard,timeo=600,wsize=1048576,rsize=1048576,nfsvers=3,tcp,actimeo=0,noacl,lock
b=bg,rg,hard,timeo=600,wsize=1048576,rsize=1048576,nfsvers=3,tcp,actimeo=0,noacl,lock

If condition is failing as it's looking for rw value from a variable at position 1 in b variable but it's in position 2 in variable b.

How can I compare the two lines even though the order of the fields is not the same?

Upvotes: 0

Views: 43

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

This script seems to work:

a="rw,bg,hard,timeo=600,wsize=1048576,rsize=1048576,nfsvers=3,tcp,actimeo=0,noacl,lock"
b="bg,rg,hard,timeo=600,wsize=1048576,rsize=1048576,nfsvers=3,tcp,actimeo=0,noacl,lock"

{ echo "$a"; echo "$b"; } |
awk -F, \
   'NR == 1 {   for (i = 1; i <= NF; i++) a[$i] = 1 }
    NR == 2 {   for (i = 1; i <= NF; i++)
                {
                    if ($i in a)
                        delete a[$i]
                    else
                    {
                        mismatch++
                        print "Unmatched item (row 2):", $i
                    }
                }
            }
    END     {
                for (i in a)
                {
                    print "Unmatched item (row 1):", i
                    mismatch++
                }
                if (mismatch > 0)
                    print mismatch, "Mismatches"
                else
                    print "Rows are the same"
            }'

Example runs:

$ bash pairing.sh
Unmatched item (row 2): rg
Unmatched item (row 1): rw
2 Mismatches
$ sed -i.bak 's/,rg,/,rw,/' pairing.sh
$ bash pairing.sh
Rows are the same
$

There are undoubtedly ways to make the script more compact, but the code is fairly straight-forward. If a field appears twice in the second row and appears once in the first row, the second one will be reported as an unmatched item. The code doesn't check for duplicates while processing the first row — it's an easy exercise to make it do so. The code doesn't print the input data for verification; it probably should.

Upvotes: 2

Related Questions