y
y
yq
Search…
Sort Keys
The Sort Keys operator sorts maps by their keys (based on their string value). This operator does not do anything to arrays or scalars (so you can easily recursively apply it to all maps).
Sort is particularly useful for diffing two different yaml documents:
1
yq -i -P 'sort_keys(..)' file1.yml
2
yq -i -P 'sort_keys(..)' file2.yml
3
diff file1.yml file2.yml
Copied!
Note that yq does not yet consider anchors when sorting by keys - this may result in invalid yaml documents if your are using merge anchors.
Note that versions prior to 4.18 require the 'eval/e' command to be specified.
yq e <exp> <file>

Sort keys of map

Given a sample.yml file of:
1
c: frog
2
a: blah
3
b: bing
Copied!
then
1
yq 'sort_keys(.)' sample.yml
Copied!
will output
1
a: blah
2
b: bing
3
c: frog
Copied!

Sort keys recursively

Note the array elements are left unsorted, but maps inside arrays are sorted
Given a sample.yml file of:
1
bParent:
2
c: dog
3
array:
4
- 3
5
- 1
6
- 2
7
aParent:
8
z: donkey
9
x:
10
- c: yum
11
b: delish
12
- b: ew
13
a: apple
Copied!
then
1
yq 'sort_keys(..)' sample.yml
Copied!
will output
1
aParent:
2
x:
3
- b: delish
4
c: yum
5
- a: apple
6
b: ew
7
z: donkey
8
bParent:
9
array:
10
- 3
11
- 1
12
- 2
13
c: dog
Copied!