shell 使用yq更新yaml中的JSON字符串字段

ccgok5k5  于 2022-11-25  发布在  Shell
关注(0)|答案(2)|浏览(273)

有一个文件sample.yaml

---
action: "want-to-update"
foo: |-
    {
        "a" : "actual A",
        "b" : "actual B",
        "c" : "actual C"
    }
---
action: "dont-want-to-update"
foo: |-
.
.
.

需要将a字段中的值从actual a更新为updated a
尝试使用yqjq更新

yq 'select(.action == "want-to-update").foo' sample.yaml | jq '.a = "updated a" | tostring' | xargs -0 -n1 -I{} yq 'select(.action == "want-to-update").foo = {}' -i sample.yaml

输出如下:

---
action: "want-to-update"
foo: |-
  {"a":"updated a","b":"actual B","c":"actual C"}
---
.
.

但我想要上面更漂亮的版本:

---
action: "want-to-update"
foo: |-
    {
        "a" : "updated A",
        "b" : "actual B",
        "c" : "actual C"
    }
---
nkoocmlb

nkoocmlb1#

使用fromjsontojson,您可以动态地对JSON进行解码和编码,因此所有这些操作只需调用yq即可完成(无需jq和命令替换):

yq -i 'select(.action == "want-to-update").foo |= (
  fromjson | .a = "updated a" | tojson
)' sample.yaml
sy5wg1nm

sy5wg1nm2#

基本上,删除tostring
第一个

相关问题