Description
Please describe your feature request.
A reverse sort on a map by it's keys. The opposite of sort_keys()
. I needed this to preserve YAML anchors before referenced as aliases.
EDIT: This could be closed as the feature was previously requested and rejected in 2022, but user advised to convert map into entries, sort + reverse, then convert list back to map. Docs could maybe be improved for an example of reverse map keys use-case?
Describe the solution you'd like
If we have data.yml
like:
name: example
x-override: &override
command: from-fragment
services:
base:
command: before-merge
image: localhost/hello-world
ext:
<<: *override
extends:
service: base
And we run a command:
yq 'sort_keys(.) | reverse' data.yml
or
yq 'sort_keys_reverse(.)' data.yml
it could output:
x-override: &override
command: from-fragment
services:
base:
command: before-merge
image: localhost/hello-world
ext:
<<: *override
extends:
service: base
name: example
Describe alternatives you've considered
See follow-up comment for more details, but these are valid alternative approaches:
yq 'to_entries | sort_by(.key) | reverse | from_entries' file.yaml
yq '(. *= load("b.yaml")) | sort_by(key | select(. != "x-*") )' a.yaml
yq '. *= (load("`b.yaml") | explode(.)) | pick(keys | filter(. != "x-*"))' a.yaml
Additional context
Reference - Related docs
https://mikefarah.gitbook.io/yq/operators/sort#sort-a-map-by-keys
https://mikefarah.gitbook.io/yq/operators/sort-keys#sort-keys-of-map