William Jiang
William Jiang

Reputation: 57

How to merge two .yaml files such that shared keys between the files uses only one of their values?

I am attempting to merge two yaml files and would like any shared keys under a specific key to use values from one of the yaml files, and not merge both. This problem may be better described using an example. GIven file1.yaml and file2.yaml, I am trying to achieve the following:

file1.yaml

name: 'file1'
paths:
  path1: 
    content: "t"
  path2:
    content: "b"

file2.yaml

name: 'file2'
paths:
  path1: 
    value: "t"

My ideal result in merging is the following file:

file3.yaml

name: 'file2'
paths:
  path1: 
    value: "t"
  path2:
    content: "b"

Specifically, I would like to overwrite any key under paths such that if both yaml files have the same key under paths, then only use the value from file2. Is there some tool that enables this? I was looking into yq but I'm not sure if that tool would work

Upvotes: 0

Views: 1228

Answers (1)

pmf
pmf

Reputation: 36033

Please specify which implementation of yq you are using. They are quite similar, but sometimes differ a lot.

For instance, using kislyuk/yq, you can use input to access the second file, which you can provide alongside the first one:

yq -y 'input as $in | .name = $in.name | .paths += $in.paths' file1.yaml file2.yaml
name: file2
paths:
  path1:
    value: t
  path2:
    content: b

With mikefarah/yq, you'd use load with providing the second file in the code, while only the first one is your regular input:

yq 'load("file2.yaml") as $in | .name = $in.name | .paths += $in.paths' file1.yaml
name: 'file2'
paths:
  path1:
    value: "t"
  path2:
    content: "b"

Upvotes: 2

Related Questions