有一个文件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
尝试更新yq
和jq
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"
}
---
使用fromjson
和tojson
,您可以动态地解码和编码JSON,因此所有这些都可以通过调用yq(不需要jq和不需要命令替换)来完成:
yq -i 'select(.action == "want-to-update").foo |= (
fromjson | .a = "updated a" | tojson
)' sample.yaml
基本上,删除tostring
json=$(
yq 'select(.action == "want-to-update").foo' sample.yaml
| jq '.a = "updated a"'
)
escaped_quotes=${json//"/\"}
yq 'select(.action == "want-to-update").foo = "'"${escaped_quotes}"'"' sample.yaml
---
action: "want-to-update"
foo: |-
{
"a": "updated a",
"b": "actual B",
"c": "actual C"
}
---
action: "dont-want-to-update"
foo: |-
"ok"