Skip to content

Split a single file into multiple by map value field #2174

Answered by mikefarah
ESipalis asked this question in Q&A
Discussion options

You must be logged in to vote

Sure:

yq 'to_entries | group_by(.value.group) | (.[] |= from_entries) | .[]' -s '.. | .group + ".yaml"'

Explanation:

  • to_entries converts the map into an entries array
  • then we can use group_by to group by the entry value group
  • Now we have and array with two elements, grouped by group name. Each of which is itself an array of entries
  • Convert the nested array elements back into objects (.[] |= from_entries)
  • Now we have an array with two elements, each of which is a map
  • Splat that array into its components .[]
  • Use the -s flag to write a file of each of the splatted components. Use .. | .group as the filename

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ESipalis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants