如何使用 yq 更改嵌套 YAML 记录中的值

How to change value in a nested YAML record using yq

我正在尝试将 bind_host: localhost 更改为 bind_host: 0.0.0.0 其中 bind_host 是 YAML 文件的第 3 层嵌套值 文件的当前值

server:
  application_connectors:
  - type: http
    port: 8989
    bind_host: localhost
  request_log:
      appenders: []
  admin_connectors:
  - type: http
    port: 8990
    bind_host: localhost

预期输出

server:
  application_connectors:
  - type: http
    port: 8989
    bind_host: 0.0.0.0
  request_log:
      appenders: []
  admin_connectors:
  - type: http
    port: 8990
    bind_host: 0.0.0.0

我正在尝试

awk '
/:$/{
  flag=""
}
/server/{
  flag=1
}
flag && NF && (/bind_host:/){
  match([=12=],/^[[:space:]]+/);
  val=substr([=12=],RSTART,RLENGTH);
  $NF="0.0.0.0";
  print val [=12=];
  next
}
1
'   config.yml

编辑:根据@inian 的回答添加图片

第二张图片

如果您正在寻找基于 kislyuk/yq 的解决方案,请使用以下代码段。它运行 jq 过滤器以将 server 中包含 bind_host 的所有对象更新为 0.0.0.0-y 标志确保结果对象在 YAML 中返回,而不是 JSON

yq -y '.server |= ( with_entries ( 
                      if   .value[] | select( keys[] | contains("bind_host") ) 
                      then .value[].bind_host = "0.0.0.0" 
                      else empty end
                    )
                  )' yaml

如果修改符合预期,请使用 -i 标志,即 yq -yi 就地保存修改。

运行

<input.yaml yq -y '((.server.application_connectors[].bind_host| select(.) ) |= gsub("localhost";"0.0.0.0") )' | \
yq -y '((.server.admin_connectors[].bind_host| select(.) ) |= gsub("localhost";"0.0.0.0") )'

你有

server:
  application_connectors:
    - type: http
      port: 8989
      bind_host: 0.0.0.0
  request_log:
    appenders: []
  admin_connectors:
    - type: http
      port: 8990
      bind_host: 0.0.0.0