Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script for string compare [duplicate]

Tags:

bash

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

like image 358
reza Avatar asked Mar 26 '26 17:03

reza


1 Answers

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;
}
like image 159
Seth Robertson Avatar answered Mar 29 '26 05:03

Seth Robertson