比较两个版本号在Bash脚本中无法正常工作。

huangapple go评论52阅读模式
英文:

Comparing two version number in bash script not working properly

问题

你好,以下是翻译好的部分:

我正在使用bash脚本工作,对这个脚本很友好。我有一组数字如下:

1.0 1.1 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9

我试图从上述数字中获取最高的数字。当我使用下面的脚本时,我得到的是1.9而不是1.16。你能帮忙吗?为了简单起见,我只取了3个数字:

a=1.9
b=1.16
max=1.9
if (( $(echo "$a < $b" | bc -l ) )); then
max=$b
fi

期望结果:1.16

实际结果:1.9

英文:

I am working in bash script and i am kind to this script. I have a number as follows

1.0 1.1 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9

I am trying to get highest number from the above numbers. When i use the below script i am getting 1.9 instead of 1.16. Could you please help on this. For simple i have take 3 number

        a=1.9
        b=1.16
        max=1.9
        if (( $(echo &quot;$a &lt; $b&quot; | bc -l ) )); then
                 max=$b
        fi

Excepted result : 1.16

Actual result : 1.9

答案1

得分: 2

如果你想找到你的版本号列表中的最大版本号,你可以使用GNU sort 而不是 bc,因为bc没有原生操作符来比较版本号:

$ list=(1.0 1.1 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9)
$ printf '%s\n' "${list[@]}" | sort -rV | head -1
1.16
  • list=(1.0 ... 1.9) 将你的数字分配给bash数组 list
  • printf '%s\n' "${list[@]}" 以每行一个数字的方式打印列表。
  • sort -rV 按版本号降序对行进行排序。
  • head -1 只打印第一行。

要找到最小值,使用 sort -V 而不是 sort -rV

英文:

If what you want is to find the maximum of your list of numbers considered as version numbers you could use GNU sort instead of bc that has no native operator to compare version numbers:

$ list=(1.0 1.1 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9)
$ printf &#39;%s\n&#39; &quot;${list[@]}&quot; | sort -rV | head -1
1.16
  • list=(1.0 ... 1.9) assigns your numbers to bash array list.
  • printf &#39;%s\n&#39; &quot;${list[@]}&quot; prints the list with one number per line.
  • sort -rV sorts the lines in decreasing order of version numbers.
  • head -1 prints only the first line.

To find the minimum use sort -V instead of sort -rV.

答案2

得分: 1

在这些情况下,使用awk更好。

#!/bin/bash

a=1.9
b=1.16
max=1.9

if awk -v num1="$a" -v num2="$b" 'BEGIN{if (num1>num2) exit 0; exit 1}'; then
  max=$a
else
  max=$b
fi

echo "最大的数是:$max"

这应该能起作用,也许你可以尝试使用for循环进行更大的比较。

英文:

In these cases using awk is better.

#!/bin/bash

a=1.9
b=1.16
max=1.9

if awk -v num1=&quot;$a&quot; -v num2=&quot;$b&quot; &#39;BEGIN{if (num1&gt;num2) exit 0; exit 1}&#39;; then
  max=$a
else
  max=$b
fi

echo &quot;The highest number is: $max&quot;

This should do the work, maybe you can try it using a for loop instead for larger comparisons.

huangapple
  • 本文由 发表于 2023年5月25日 14:15:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定