Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort document by key #1024

Closed
wake42 opened this issue Nov 27, 2021 · 4 comments
Closed

Sort document by key #1024

wake42 opened this issue Nov 27, 2021 · 4 comments

Comments

@wake42
Copy link

wake42 commented Nov 27, 2021

Please describe your feature request.
I wish I could use yq to sort a multidocument file based on a key.

Describe the solution you'd like
Given a file

name: Beta
data:
  rank: bla bla
---
name: Alfa
data:
  rank: bla bla
---
name: Gamma
data:
  rank: bla bla

I would like to sort the order of the included yaml document given a key, so that the above, sorted by key .name would become

name: Alfa
data:
  rank: bla bla
---
name: Beta
data:
  rank: bla bla
---
name: Gamma
data:
  rank: bla bla
@mikefarah
Copy link
Owner

This can now be done with 4.16.1 with the new sort_by operator. This operator sorts arrays, so you first need to put the docs into an array, sort, then split them out again:

yq ea '[.] | sort_by(.name) | .[] | splitDoc' file.yaml

@Zebradil
Copy link

Zebradil commented Mar 8, 2022

Initial comment

The suggestion doesn't seem to work:

cat << EOF | yq '[.] | sort_by(.name) | .[] | splitDoc'
name: Beta
data:
  rank: bla bla
---
name: Alfa
data:
  rank: bla bla
---
name: Gamma
data:
  rank: bla bla
EOF
name: Beta
data:
  rank: bla bla
name: Alfa
data:
  rank: bla bla
name: Gamma
data:
  rank: bla bla
yq (https://github.com/mikefarah/yq/) version 4.21.1

My bad, eval-all is important — it works.

@eripa
Copy link

eripa commented Feb 2, 2023

Hello @mikefarah,

sorry for bringing this thread back from the dead. But is it possible to have second (and third etc) key sorting like below. I.e. first sort all documents on X, but for if the value is the same, use the second key Y to sort within those?

i.e.

name: Beta
other: Epsilon
---
name: Alfa
other: Gamma
---
name: Beta
other: Delta

result (Beta Delta comes before Beta Epsilon):

name: Alfa
other: Gamma
---
name: Beta
other: Delta
---
name: Beta
other: Epsilon

Thanks a lot 🙏

@mikefarah
Copy link
Owner

Not yet - but that would be good to add; feel free to raise a separate issue so I can track it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants