Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq sort by version as string

I'm trying to sort the following json reponse to pick the latest version:

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

Correct sorting should be:

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

I'm currently able to do part of the job. It's working for simple cases (all version part major/minor/bug has the same number of digits).

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

The best way to do it in my mind should be to add a multiplication the each part. Example:

# 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

Does anybody have an idea to implement this? 🙂

like image 393
brcebn Avatar asked May 10 '26 09:05

brcebn


1 Answers

Turn each component into a number, then sort on the array of integers.

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

Output:

[
  {
    "TagVersion": "1.0.9"
  },
  {
    "TagVersion": "1.0.10"
  },
  {
    "TagVersion": "1.0.11"
  },
  {
    "TagVersion": "1.0.77"
  },
  {
    "TagVersion": "1.1.8"
  }
]
like image 154
Amadan Avatar answered May 13 '26 04:05

Amadan