Как добавить последовательные номера сообщений в команде jq

Я не мог понять, как это сделать, поэтому спросил здесь.

[
  {
    "message" : "This is",
    "Identity" : "1"
  },
  {
    "message" : " a car",
    "Identity" : "2"
  },
  {
    "message" : "My Job",
    "Identity" : "11"
  },
  {
    "message" : "Is a ",
    "Identity" : "12"
  },
  {
    "message" : "Student",
    "Identity" : "13"
  }
]



1 and 2, 11 and 12 are made up of consecutive numbers.
I would like to group messages made up of consecutive numbers like this and add them starting from the smallest order.
[
  {
    "message" : "This is a car"
  },
  {
    "message" : "My Job Is a Student"
  }
]

I can't remember the mathematical formula, so I would appreciate if you could help me with the formula.

1
66
1

Ответ:

Решено

Преобразуйте все строки .Identity в числа и удалите начальные и конечные пробелы из полей .message (для чистого интервала, как в желаемом выводе). Затем выполните итерацию по массиву и либо добавьте сообщение элемента к последнему сообщению (с повторным включением одного пробела между ними), либо сам элемент в массив, в зависимости от разницы в их полях .Identity. Наконец, удалите все оставшиеся поля .Identity.

map(.Identity |= tonumber | .message |= (ltrimstr(" ") | rtrimstr(" ")))
| reduce .[] as $i ([];
    if last.Identity != $i.Identity - 1 then . += [$i] else
      last.Identity += 1 | last.message += " " + $i.message
    end
  )
| del(.[].Identity)
[
  {
    "message": "This is a car"
  },
  {
    "message": "My Job Is a Student"
  }
]

Демо

Предполагается, что входной массив уже отсортирован. Если нет, сначала выполните сортировку, начиная с map(.Identity |= tonumber | .message |= (…)) | sort_by(.Identity) | reduce ….