jq 按版本排序为字符串

jq sort by version as string

我正在尝试对以下 json 响应进行排序以选择最新版本:

[
    {
        "TagVersion": "1.0.11"
    },
    {
        "TagVersion": "1.1.8"
    },
    {
        "TagVersion": "1.0.10",
    },
    {
        "TagVersion": "1.0.9",
    },
    {
        "TagVersion": "1.0.77"
    }
]

正确的排序应该是:

    {
        "TagVersion": "1.0.9",
    },
    {
        "TagVersion": "1.0.10",
    },
    {
        "TagVersion": "1.0.11"
    },
    {
        "TagVersion": "1.0.77"
    },
    {
        "TagVersion": "1.1.8"
    }

我目前可以完成部分工作。它适用于简单的情况(所有版本部分 major/minor/bug 具有相同的位数)。

jq -r [.[]]|max_by(.TagVersion|split(".") | map(tonumber)

在我看来最好的方法应该是对每个部分进行乘法运算。示例:

# With condition than every "part" as a maximum of 2 digits. It won't work with 3 digits

# Version 1.23.87

1 * 1000 + 23 * 10 + 87 = 1317

# Version 3.0.0
1 * 1000 + 0 * 10 + 0 = 3000

# Version 1.89.78
1 * 1000 + 89*10 + 78 = 1968

有人有实现这个的想法吗?

将每个分量变成一个数字,然后对整数数组进行排序。

jq 'sort_by(.TagVersion|split(".")|map(tonumber))'

输出:

[
  {
    "TagVersion": "1.0.9"
  },
  {
    "TagVersion": "1.0.10"
  },
  {
    "TagVersion": "1.0.11"
  },
  {
    "TagVersion": "1.0.77"
  },
  {
    "TagVersion": "1.1.8"
  }
]