y
y
yq
Search…
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.
Note that versions prior to 4.18 require the 'eval/e' command to be specified.
yq e <exp> <file>

Sort by string field

Given a sample.yml file of:
1
- a: banana
2
- a: cat
3
- a: apple
Copied!
then
1
yq 'sort_by(.a)' sample.yml
Copied!
will output
1
- a: apple
2
- a: banana
3
- a: cat
Copied!

Sort descending by string field

Use sort with reverse to sort in descending order.
Given a sample.yml file of:
1
- a: banana
2
- a: cat
3
- a: apple
Copied!
then
1
yq 'sort_by(.a) | reverse' sample.yml
Copied!
will output
1
- a: cat
2
- a: banana
3
- a: apple
Copied!

Sort array in place

Given a sample.yml file of:
1
cool:
2
- a: banana
3
- a: cat
4
- a: apple
Copied!
then
1
yq '.cool |= sort_by(.a)' sample.yml
Copied!
will output
1
cool:
2
- a: apple
3
- a: banana
4
- a: cat
Copied!

Sort array of objects by key

Note that you can give sort_by complex expressions, not just paths
Given a sample.yml file of:
1
cool:
2
- b: banana
3
- a: banana
4
- c: banana
Copied!
then
1
yq '.cool |= sort_by(keys | .[0])' sample.yml
Copied!
will output
1
cool:
2
- a: banana
3
- b: banana
4
- c: banana
Copied!

Sort is stable

Note the order of the elements in unchanged when equal in sorting.
Given a sample.yml file of:
1
- a: banana
2
b: 1
3
- a: banana
4
b: 2
5
- a: banana
6
b: 3
7
- a: banana
8
b: 4
Copied!
then
1
yq 'sort_by(.a)' sample.yml
Copied!
will output
1
- a: banana
2
b: 1
3
- a: banana
4
b: 2
5
- a: banana
6
b: 3
7
- a: banana
8
b: 4
Copied!

Sort by numeric field

Given a sample.yml file of:
1
- a: 10
2
- a: 100
3
- a: 1
Copied!
then
1
yq 'sort_by(.a)' sample.yml
Copied!
will output
1
- a: 1
2
- a: 10
3
- a: 100
Copied!

Sort, nulls come first

Given a sample.yml file of:
1
- 8
2
- 3
3
- null
4
- 6
5
- true
6
- false
7
- cat
Copied!
then
1
yq 'sort' sample.yml
Copied!
will output
1
- null
2
- false
3
- true
4
- 3
5
- 6
6
- 8
7
- cat
Copied!
Last modified 4mo ago