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

1
  • 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. Commented Jun 29, 2011 at 15:00

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

not all sort calls support -V
@reza: Which is why I included an alternative because my sort at one point didn't support -V.
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

5 Comments

[[ 2.0.10 < 2.0.9 ]] && echo "less" wrote "less" on my system.
@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";
yes seth is correct, this is not the right answer
@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.
I am comparing versions and I should have used a more accurate title. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.