Search code examples
arrayssortingyamlyq

yq (GO/Mike Farah) sort all arrays recursively?


This is probably related to another question I posted: yq (GO/Mike Farah) uniquify all arrays recursively

Mike Farah's yq provides documentation for sorting arrays but I'm having trouble figuring how to apply that to a list that is nested deeper

Input

classes:
  driver:
    fields:
      - height
      - weight
      - age
  vehicle:
    fields:
      - model
      - manufacturer
      - color
      - year

Desired output

classes:
  driver:
    fields:
      - age
      - height
      - weight
  vehicle:
    fields:
      - color
      - manufacturer
      - model
      - year

Naively trying to sort globally

cat to_sort.yaml | yq 'sort'

Error: node at path [] is not an array (it's a !!map)

And if it takes arguments, I don't know what to provide. I don't want to just sort one explicit path, but I did try this:

cat to_sort.yaml | yq 'sort(classes.driver.fields)'

Error: 1:6: invalid input text "classes.driver.f..."

I have seen some yq examples where one has to do a select operation first, but I don't know what to try in this case.


Solution

  • yq e '(... | select(type == "!!seq")) |= sort' input
    

    Will recursively loop over all the values, and select() those with type !!seq and update (|=) those with sort.

    Applying OP's input to that filter gives:

    classes:
      driver:
        fields:
          - age
          - height
          - weight
      vehicle:
        fields:
          - color
          - manufacturer
          - model
          - year