How to compare two strings in dot separated version format in Bash?

前端 未结 29 1343
慢半拍i
慢半拍i 2020-11-22 06:52

Is there any way to compare such strings on bash, e.g.: 2.4.5 and 2.8 and 2.4.5.1?

29条回答
  •  悲哀的现实
    2020-11-22 07:14

    Another approach(modified version of @joynes) that compares dotted versions as asked in the question
    (i.e "1.2", "2.3.4", "1.0", "1.10.1", etc.).
    The maximum number of positions has to be known in advance. The approach expects max 3 version positions.

    expr $(printf "$1\n$2" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != $2
    

    example usage:

    expr $(printf "1.10.1\n1.7" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != "1.7"
    

    returns: 1 since 1.10.1 is bigger than 1.7

    expr $(printf "1.10.1\n1.11" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != "1.11"
    

    returns: 0 since 1.10.1 is lower than 1.11

提交回复
热议问题