【问题标题】:Insert multiple lines of one attribute in yaml file with yq v4.x使用 yq v4.x 在 yaml 文件中插入一个属性的多行
【发布时间】:2021-09-20 02:12:15
【问题描述】:

在 input.yaml 中存储了一个动态属性,我想将其插入到现有的 yaml 文件中(命名为 original.yaml)。该属性有多行。

这两个文件看起来像: 输入.yaml:

- name: bob
  spec: {}

原始.yaml:

spec:
    names:
      - name: alice
        spec: {}

我的目标是将 input.yaml 内容放在 original.yaml spec.names 下。 我尝试使用 yq 版本 4:

env=$(cat input.yaml)
yq eval '.spec.names + strenv(env)' original.yaml > result.yaml

我得到了什么:

spec:
  names:
    - name: alice
      spec: {}
    - |-
      - name: bob
        spec: {}

第 5 行有一个不需要的 - |-,我预计会出现以下输出:

spec:
  names:
    - name: alice
      spec: {}
    - name: bob
      spec: {}

任何建议将不胜感激。

【问题讨论】:

    标签: yaml yq


    【解决方案1】:

    这个想法是正确的,但您不应该使用 strenv() 函数,它将您的输入格式化为 YAML 字符串类型。您的names 记录是一个映射数组,因此您需要保留原始类型,只需使用env

    因此,有了它并避免 cat 并使用 shell 输入重定向(应该在 bash/zsh/ksh 上工作),您可以这样做

    item="$(< input.yaml)" yq e '.spec.names += env(item)' original.yaml
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 2017-08-18
      • 2012-07-21
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多