Search code examples
dockertagsjqgcloud

Sort strings in array by length using jq


I am grabbing a list of all docker tags from GCP via the gcloud cli

gcloud container images list-tags gcr.io/my_image --format=json | jq -S .[].tags

the output:

[
  "build.160",
  "ed37ba0ea1f31d62ff48ef817addd30c8be9952c"
]
[
  "5cd7190a96f633cfb8b5fa0f876f147dbe700dad",
  "build.161"
]
[
  "9a9f030fcf7544565b9ebf8ba37330b649e156ba",
  "build.159"
]

Is there a way to sort the values to keep consistency? That way it can look like this:

[
  "ed37ba0ea1f31d62ff48ef817addd30c8be9952c",
  "build.160"
]
[
  "5cd7190a96f633cfb8b5fa0f876f147dbe700dad",
  "build.161"
]
[
  "9a9f030fcf7544565b9ebf8ba37330b649e156ba",
  "build.159"
]

Solution

  • You can do sort_by on the length of the strings in the array and reverse the order to keep the longest string first. Remove the reverse function to keep the shortest string first

    sort_by(length) | reverse