【发布时间】:2021-03-17 22:30:44
【问题描述】:
我有一个包含数组的 YAML 文档。我想使用来自 mikefarah 的 yq version 4 有条件地向该数组的元素添加属性。
这是一个示例 YAML 文档。
name: "My Pets"
pets:
- name: "cat"
age: 8
- name: "dog"
age: 3
- name: "mouse"
age: 1
我想把它变成,
name: "My Pets"
pets:
- name: "cat"
age: 8
shots: cat.upToDate
- name: "dog"
age: 3
shots: dog.upToDate
- name: "mouse"
age: 1
shots: mouse.upToDate
我们将shots 属性添加到pets 的每个元素。 shots 的值应该是 name 的任何值,点,upToDate。
我正在尝试这样的事情,
yq eval '.pets[] | select(.name == "cat").shots = "cat.upToDate"' test.yaml
但这会产生,
name: "cat"
age: 8
shots: cat.upToDate
name: "dog"
age: 3
name: "mouse"
age: 1
我需要保留整个原始 YAML 文档并插入 shots 属性。
这很接近,但缺少所有其他宠物。
yq eval '.pets = (.pets[] | select(.name == "cat").shots = "cats.upToDate")' test.yaml
它产生,
name: "My Pets"
pets:
name: "cat"
age: 8
shots: cats.upToDate
我在想也许我们可以将宠物的名字存储在一个变量中并在以后引用它,但是 v4 今天对我来说是全新的。
我希望有一个单行,这样我就不必过滤.name。这个数组的元素少于 10 个,因此我可以轻松地硬编码名称并调用 yq 10 次。
有什么想法或建议吗?非常感谢,韦尔登
【问题讨论】:
-
这真的很接近。如果
cat可以动态计算,这将起作用:yq eval '.pets = (.pets | .[].shots = "cat.upToDate")' test.yaml -
这更接近了,但它对每个
shots值重复cat:yq eval '.pets = (.pets | .[].shots = .[].name + ".upToDate")' test.yaml