3

Possible Duplicate:
Bash. How compare two strings in “version” format

All,

I need a good algorithm, script to compare "2.0.9" to "2.0.10" 2.0.9 is less than 2.0.10

"2.0.1" is less than "2.0.9" "2.0.9" is less than "2.0.92"

See the picture? this is on the Mac OS 10.6

Community
  • 1
  • 1
reza
  • 5,972
  • 15
  • 84
  • 126
  • this might be a duplicate, but the duplicate had the wrong answer. So instead one reusing that, I opened a new one. I should have used a more descriptive and accurate title. – reza Jun 29 '11 at 15:00

2 Answers2

1

Take a look at sort -V and ls -v source code.

Also this is a program I wrote before those other programs learned about version sorting.

#!/usr/bin/perl

@S = <>;
print sort byglob @S;


######################################################################
#
# Sorting function which sorts numerically for numerical parts,
# alphabetically otherwise
# 
sub byglob
{
  my($A) = $a;
  my($B) = $b;
  my($c,$d,$e);

  while ($A && $B)
    {
      $A =~ s/^([0-9]+|[^0-9]+)//;
      $c = $1;
      $B =~ s/^([0-9]+|[^0-9]+)//;
      $d = $1;

      if ($c =~ /\d/ && $d =~ /\d/)
        {
          $e = $c <=> $d;
        }
      else
        {
          $e = $c cmp $d;
        }
      return $e if ($e);
    }
  return $a cmp $b;
}
Seth Robertson
  • 30,608
  • 7
  • 64
  • 57
0

In bash compare them like this using arithmetic operator < inside arithmetic expression brackets [[ and ]] :

x=2.0.9
y=2.0.92
[[ $x < $y ]] && echo "less"

OUTPUT

less
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    `[[ 2.0.10 < 2.0.9 ]] && echo "less"` wrote "less" on my system. – Seth Robertson Jun 27 '11 at 17:51
  • @Seth Robertson: That is correct behavior because in arithmetic `2.0.10` is indeed less than `2.0.9`. However if you compare `2.0.10` with `2.0.09` then it will NOT echo `"less"`; – anubhava Jun 27 '11 at 17:56
  • yes seth is correct, this is not the right answer – reza Jun 27 '11 at 18:01
  • @reza Please read my comment about arithmetic number comparison above. btw are you comparing versions? if yes update the requirement in your question properly and then you'll get better answers. – anubhava Jun 27 '11 at 18:08
  • I am comparing versions and I should have used a more accurate title. Thanks – reza Jun 29 '11 at 15:02