我有一个如下所示的 yaml 文件。
test:
test_1:
fact_1: Present
fact_2: value_1
tag: tagvalue
test_2:
fact_1: NotPresent
fact_2: null
tag: null
test_3:
fact_1: Present
fact_2: value_2
tag: 1.1
fact_3: 60
test_4:
fact_1: Present
fact_2: value_3
tag: 5.1
我想更新这个 yaml 文件中 test_1 部分下的标签。请注意,我不知道该标签的当前值,也不知道该 yaml 文件中的确切键和键的顺序。这也是我完整的 yaml 文件的一个子部分。
我试过用正则表达式来识别这个标签值,然后用sed命令更新文件。
sed -i 's/\(\stest_1:[\s\S]*?tag\s*:\s*)(\S+)/\1new_tag/' test.yaml
当我单独测试正则表达式时,它确定了 test_1 部分。但是当我执行上面的 sed 命令时,它不会改变任何东西。我能知道这里有什么问题吗?
sed
不是 YAML
解析器,而是一个面向文本行流的工具。
使用 Python 或 go
yq
:
$ yq '.test.test_1.tag="new_tag"' file.yaml
{
"test": {
"test_1": {
"fact_1": "Present",
"fact_2": "value_1",
"tag": "new_tag"
},
"test_2": {
"fact_1": "NotPresent",
"fact_2": null,
"tag": null
},
"test_3": {
"fact_1": "Present",
"fact_2": "value_2",
"tag": 1.1,
"fact_3": 60
},
"test_4": {
"fact_1": "Present",
"fact_2": "value_3",
"tag": 5.1
}
}
}