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.
CodePudding user response:
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
...
: Recursive Descent
CodePudding user response:
You have to first traverse there, then update the array (here, using the update |=
operator).
Either one after another:
yq '
.classes.driver.fields |= sort
| .classes.vehicle.fields |= sort
' to_sort.yaml
Or both at once:
yq '
(.classes.driver.fields, .classes.vehicle.fields) |= sort
' to_sort.yaml
Both output
classes:
driver:
fields:
- age
- height
- weight
vehicle:
fields:
- color
- manufacturer
- model
- year