mirror of
https://github.com/mikefarah/yq.git
synced 2024-12-19 20:19:04 +00:00
1.8 KiB
1.8 KiB
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).
Note that at this stage, yq
only sorts scalar fields.
{% hint style="warning" %} Note that versions prior to 4.18 require the 'eval/e' command to be specified.
yq e <exp> <file>
{% endhint %}
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 array in place
Given a sample.yml file of:
cool:
- a: banana
- a: cat
- a: apple
then
yq '.cool |= sort_by(.a)' sample.yml
will output
cool:
- a: apple
- a: banana
- a: cat
Sort 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: banana
then
yq '.cool |= sort_by(keys | .[0])' sample.yml
will output
cool:
- a: banana
- b: banana
- c: banana
Sort 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: 4
then
yq 'sort_by(.a)' sample.yml
will output
- a: banana
b: 1
- a: banana
b: 2
- a: banana
b: 3
- a: banana
b: 4
Sort by numeric field
Given a sample.yml file of:
- a: 10
- a: 100
- a: 1
then
yq 'sort_by(.a)' sample.yml
will output
- a: 1
- a: 10
- a: 100
Sort, nulls come first
Given a sample.yml file of:
- 8
- 3
- null
- 6
- true
- false
- cat
then
yq 'sort' sample.yml
will output
- null
- false
- true
- 3
- 6
- 8
- cat