如何合并两个 .yaml 文件,以便文件之间共享的键只使用它们的一个值?

huangapple go评论61阅读模式
英文:

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

问题

我试图合并两个YAML文件,并希望在特定键下共享的任何键都使用其中一个YAML文件的值,而不是合并两者。通过示例更好地描述这个问题可能会更清晰。给定file1.yaml和file2.yaml,我试图实现以下目标:

file1.yaml

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

file2.yaml

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

我希望合并的理想结果是以下文件:

file3.yaml

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

具体来说,我希望覆盖任何在paths下的键,以便如果两个YAML文件都具有相同的键在paths下,那么只使用file2中的值。是否有一些工具可以实现这一点?我正在研究yq,但不确定该工具是否适用。

英文:

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

答案1

得分: 2

请指定您正在使用的 yq 实现。它们非常相似,但有时差异很大。

例如,使用 kislyuk/yq,您可以使用 input 来访问第二个文件,您可以将其与第一个文件一起提供:

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

而对于 mikefarah/yq,您将在代码中提供第二个文件,仅将第一个文件作为常规输入:

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

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"

huangapple
  • 本文由 发表于 2023年2月18日 08:26:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定