开发者

bash script for string compare [duplicate]

开发者 https://www.devze.com 2023-03-16 04:17 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Bash. How compare two strings in “version” format
This question already has answers here: Closed 11 years ago.

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.开发者_如何学JAVA0.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


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;
}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消