user3060455
user3060455

Reputation: 1

Comparing strings with numbers in shell script

I am trying to compare to build numbers and echo which is greater. Here is a script i wrote

    New_Cycle_Num='c4.10'
    Old_Cycle_Num='c4.9'
    if  [ "$New_Cycle_Num" == "$Old_Cycle_Num" ];
    then echo 'both are equal'
    elif [ "$New_Cycle_Num" "<" "$Old_Cycle_Num" ]];
    then echo 'New_Cycle_Num is less than Old_Cycle_Num'
    else echo 'New_Cycle_Num is greater than Old_Cycle_Num'
    fi

My script gives me ioutput as 'New_Cycle_Num is less than Old_Cycle_Num" instead of last statement. why is c4.10 compared to be less than c4.9? any help to correct this ?? Many thanks!!

Upvotes: 0

Views: 549

Answers (1)

glenn jackman
glenn jackman

Reputation: 246754

You get the result you get because with lexical comparison, comparing the 4th character, "1" appears before "9" in the dictionary (in the same sense that "foobar" would appear before "food", even though "foobar" is longer).

Tools like ls and sort have a "version sorting" option, which will be useful here, albeit somewhat awkward:

New_Cycle_Num='c4.10'
Old_Cycle_Num='c4.9'
if [[ $New_Cycle_Num == $Old_Cycle_Num ]]; then
    echo 'equal'
else
    before=$(printf "%s\n" "$New_Cycle_Num" "$Old_Cycle_Num")
    sorted=$(sort -V <<<"$before")
    if [[ $before == $sorted ]]; then
        echo 'New_Cycle_Num is less than Old_Cycle_Num'
    else
        echo 'New_Cycle_Num is greater than Old_Cycle_Num'
    fi
fi
New_Cycle_Num is greater than Old_Cycle_Num

I can't think of a great alternative. There might be

echo -e "c4.10\nc4.9" | 
perl -MSort::Versions -E '
  $a=<>; $b=<>; chomp($a, $b); $c=versioncmp($a,$b);
  say "$a is ". ($c==0 ? "equal to" : $c < 0 ? "less than" : "greater than") . " $b"
'
c4.10 is greater than c4.9

But you have to install Sort::Versions from CPAN.

Upvotes: 1

Related Questions