Sort

Sorts an array. Use sort to sort an array as is, or sort_by(exp) to sort by a particular expression (e.g. subfield).

To sort by descending order, pipe the results through the reverse operator after sorting.

Note that at this stage, yq only sorts scalar fields.

Sort by string field

Given a sample.yml file of:

- a: banana
- a: cat
- a: apple

then

yq 'sort_by(.a)' sample.yml

will output

- a: apple
- a: banana
- a: cat

Sort by multiple fields

Given a sample.yml file of:

then

will output

Sort descending by string field

Use sort with reverse to sort in descending order.

Given a sample.yml file of:

then

will output

Sort array in place

Given a sample.yml file of:

then

will output

Sort array of objects by key

Note that you can give sort_by complex expressions, not just paths

Given a sample.yml file of:

then

will output

Sort a map

Sorting a map, by default this will sort by the values

Given a sample.yml file of:

then

will output

Sort a map by keys

Use sort_by to sort a map using a custom function

Given a sample.yml file of:

then

will output

Sort is stable

Note the order of the elements in unchanged when equal in sorting.

Given a sample.yml file of:

then

will output

Sort by numeric field

Given a sample.yml file of:

then

will output

Sort by custom date field

Given a sample.yml file of:

then

will output

Sort, nulls come first

Given a sample.yml file of:

then

will output

Last updated

Was this helpful?