1

I have the following sample data:

{
    "Images": [
        {
            "Name": "CoreOS-alpha-1939.0.0-hvm",
            "CreationDate": "2014-12-24T23:00:48.000Z"
        },
        {
            "Name": "CoreOS-stable-522.3.0",
            "CreationDate": "2014-12-24T23:00:48.000Z"
        },
        {
            "Name": "CoreOS-stable-600.3.0",
            "CreationDate": "2019-12-24T23:00:48.000Z"
        }
    ]
}

I'm trying to get the Name of the most recent (by CreationDate) image that contains "stable" in its Name.

My naive attempt is:

jq '.Images[] | select(.Name | contains("stable")) |= sort_by(.CreationDate)' data.json

However this is giving me an error, and would only sort them by CreationDate (not only return the latest one)

peak
  • 105,803
  • 17
  • 152
  • 177
Juicy
  • 11,840
  • 35
  • 123
  • 212

1 Answers1

2
$ jq -r '.Images | map(select(.Name | index("stable"))) | max_by(.CreationDate).Name' file
CoreOS-stable-600.3.0

since contains is a bit overkill for checking a string for its containment in another string, index is used instead.
max_by is used because it avoids sorting and yields the element with max. CreationDate.

oguz ismail
  • 1
  • 16
  • 47
  • 69