Use yq to merge duplicate map keys in a single file #2120
-
Is there way to use yq to merge duplicate map keys in a single (incorrect) yaml file? yq handles this nicely for multiple yaml files already. For example, if file1.yaml contains this:
and file2.yaml contains this:
then yq can merge them with
Although map keys must be unique within a single file, it can be useful if yq could handle duplicates using its merge feature, just as if the duplicate keys were in separate files as above. For example, consider file3.yaml created by
Passing file3.yaml twice using,
However, the desired result is the same as when the duplicate map keys are in separate files:
Is there an incantation to yq that will take a single (incorrect) yaml file such as file3.yaml above and merge the duplicate map keys? Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
A workaround to do this in two steps is to split the yaml file with duplicate map keys into multiple files each with a single map key and then run yq to merge them. Like this:
However, I suspect this is possible with yq in one step, somehow. Anyone know the yq grammar well enough to say? |
Beta Was this translation helpful? Give feedback.
-
Sorry - because it's (as you pointed out) not valid yaml; the underlying yaml decoder doesn't support reading both those values for the same map key. You'd have to do a pre-processing step like @maartenSXM has got and produce valid yaml content before using yq. Note that you could also split the file into several 'documents' like so:
And then merge those documents together... |
Beta Was this translation helpful? Give feedback.
-
Hi @mikefarah, Your reply helped me reduce the number of temporary files created down to one by doing this:
This solution will scale to very large numbers of map keys since it does not generate one file per map key. Thank you. |
Beta Was this translation helpful? Give feedback.
Hi @mikefarah, Your reply helped me reduce the number of temporary files created down to one by doing this:
This solution will scale to very large numbers of map keys since it does not generate one file per map key. Thank you.