Search code examples
awkstring-comparison

How to strictly compare two long numeric string in awk


I wrote some awk script to process some data, and found the result unexpected.

I found the root cause is that the following string comparison is not correct

echo "59558711052462309110012 59558711052462313120012"|awk '{print $1;print $2;print ($1==$2)?"eq":"ne"}'

The result is

59558711052462309110012
59558711052462313120012
eq

I guess the reason is that awk treats the two numeric strings as numbers, and cuts off them to compare. My question is that how can I strictly compare the two strings in awk.


Solution

  • Force a string comparison by telling awk that at least one of the operands IS a string by concatenating that operand with the null string:

    echo "59558711052462309110012 59558711052462313120012"|
    awk '{print $1;print $2;print ($1""==$2)?"eq":"ne"}'
    59558711052462309110012
    59558711052462313120012
    ne