我试图比较构建数字和回声更大。这是我写的脚本
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
我的脚本给我ioutput作为'New_Cycle_Num小于Old_Cycle_Num'而不是最后一个语句。为什么c4.10比较小于c4.9?任何帮助纠正这个?非常感谢!!
答案 0 :(得分:1)
你得到你得到的结果,因为通过词汇比较,比较第四个字符,“1”出现在字典中的“9”之前(同样意义上“foobar”将出现在“食物”之前,即使“foobar” “更长了。”
像ls
和sort
这样的工具有一个“版本排序”选项,这在这里很有用,虽然有些尴尬:
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
我想不出一个很好的选择。可能有
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
但您必须从CPAN安装Sort :: Versions。