考虑以下hello.yaml
:
foos:
- foo: foo1
bar: hello
- foo: foo2
bar: world
如果我想更新foo = "foo1"
中bar
的值,我可以调用以下命令:
yq '( .foos[] | select(.foo == "foo1") | .bar) |= "goodbye cruel"' hello.yaml
正确输出:
foos:
- foo: foo1
bar: goodbye cruel
- foo: foo2
bar: world
但是,如果我不知道我有一个匹配的项,我想插入适当的条目,例如yq '( .foos[] | select(.foo == "foo3") | .bar) ...
将输出
foos:
- foo: foo1
bar: hello
- foo: foo2
bar: world
- foo: foo3
bar: goodbye cruel
有没有办法在yq
"upsert"数组,或我必须评估是否存在关键前期和执行两个命令来插入或更新?
多谢
就像我说的;没有加注操作(目前)。这就是我要做的——不确定是否有更好的方法?
yq '
with(.foos ;
select( all_c(.foo != "foo3")) | . += {"foo": "foo3"}
) |
(.foos[] | select(.foo == "foo3") | .bar) = "cool"
' hello.yaml
解释:
- 在
with
块中,匹配不有foo: foo3的数组,并添加 - 接下来,找到所有带有foo: foo3的元素并更新它们。
免责声明:我写的是yq