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: applethen
yq 'sort_by(.a)' sample.ymlwill output
- a: apple
- a: banana
- a: catSort by multiple fields
Given a sample.yml file of:
- a: dog
- a: cat
b: banana
- a: cat
b: applethen
yq 'sort_by(.a, .b)' sample.ymlwill output
- a: cat
b: apple
- a: cat
b: banana
- a: dogSort descending by string field
Use sort with reverse to sort in descending order.
Given a sample.yml file of:
- a: banana
- a: cat
- a: applethen
yq 'sort_by(.a) | reverse' sample.ymlwill output
- a: cat
- a: banana
- a: appleSort array in place
Given a sample.yml file of:
cool:
- a: banana
- a: cat
- a: applethen
yq '.cool |= sort_by(.a)' sample.ymlwill output
cool:
- a: apple
- a: banana
- a: catSort array of objects by key
Note that you can give sort_by complex expressions, not just paths
Given a sample.yml file of:
cool:
- b: banana
- a: banana
- c: bananathen
yq '.cool |= sort_by(keys | .[0])' sample.ymlwill output
cool:
- a: banana
- b: banana
- c: bananaSort a map
Sorting a map, by default this will sort by the values
Given a sample.yml file of:
y: b
z: a
x: cthen
yq 'sort' sample.ymlwill output
z: a
y: b
x: cSort a map by keys
Use sort_by to sort a map using a custom function
Given a sample.yml file of:
Y: b
z: a
x: cthen
yq 'sort_by(key | downcase)' sample.ymlwill output
x: c
Y: b
z: aSort is stable
Note the order of the elements in unchanged when equal in sorting.
Given a sample.yml file of:
- a: banana
b: 1
- a: banana
b: 2
- a: banana
b: 3
- a: banana
b: 4then
yq 'sort_by(.a)' sample.ymlwill output
- a: banana
b: 1
- a: banana
b: 2
- a: banana
b: 3
- a: banana
b: 4Sort by numeric field
Given a sample.yml file of:
- a: 10
- a: 100
- a: 1then
yq 'sort_by(.a)' sample.ymlwill output
- a: 1
- a: 10
- a: 100Sort by custom date field
Given a sample.yml file of:
- a: 12-Jun-2011
- a: 23-Dec-2010
- a: 10-Aug-2011then
yq 'with_dtf("02-Jan-2006"; sort_by(.a))' sample.ymlwill output
- a: 23-Dec-2010
- a: 12-Jun-2011
- a: 10-Aug-2011Sort, nulls come first
Given a sample.yml file of:
- 8
- 3
- null
- 6
- true
- false
- catthen
yq 'sort' sample.ymlwill output
- null
- false
- true
- 3
- 6
- 8
- catLast updated
Was this helpful?