如何用yq将two.yaml内容合并到one.yaml的top-level节点下?
用yq实现将two.yaml内容合并到one.yaml的top-level节点下
问题描述
想要将two.yaml中的所有内容合并到one.yaml的top-level节点下,是否可以通过yq实现?
现有文件内容
one.yaml
top-level: a: create: false b: one: "one" two: "two"
two.yaml
application: executable: test a: name: test b: three: "three" four: "four" c: enabled: true
预期结果
top-level: application: executable: test a: create: false name: test b: one: "one" two: "two" three: "three" four: "four" c: enabled: true
之前尝试用ireduce但未成功,命令如下:
yq 'load("one.yaml") as $d1| load("two.yaml") as $d2 | ($d1 | keys | .[]) as $i ireduce($d2; .top-level[$i] = .top-level[$i] // $d2.top-level[$i])' one.yaml
解决方案
完全可以用yq实现这个需求,针对主流的两个yq版本,分别提供可行命令:
1. 使用mikefarah/yq(v4+,最常用版本)
用eval-all模式加载两个文件,通过深度合并操作符*=将two.yaml的所有内容合并到one.yaml的top-level节点下:
yq eval-all 'select(fileIndex == 0) as $one | select(fileIndex == 1) as $two | $one | .top-level *= $two' one.yaml two.yaml
逻辑说明:
eval-all:开启多文件处理模式select(fileIndex == 0):选取第一个文件(one.yaml)作为基准结构select(fileIndex == 1):选取第二个文件(two.yaml)作为待合并的内容.top-level *= $two:将two.yaml的所有节点深度合并到top-level下,已有节点(如a、b)的子属性会自动合并,不会覆盖原有值
2. 使用kislyuk/yq(Python实现版本)
结合jq语法实现深度合并:
yq -y 'input as $two | .top-level = ($.top-level * $two)' one.yaml two.yaml
结果验证
执行对应命令后,输出的YAML结构会和预期结果完全一致:既保留one.yaml中top-level节点的原有属性,又将two.yaml的所有内容合并到该节点下,子节点自动合并补充。
内容的提问来源于stack exchange,提问作者C. Tester
相关产品推荐
相关产品推荐

