如何用yq命令筛选YAML文件中含port字段的顶级键?
筛选包含指定字段的YAML顶级键的yq命令
原始YAML文件
service1: host: s1 port: 27000 service2: host: s2 port: 27001 service3: host: s3 service4: host: s4 port: 27004
需求
列出所有对应对象包含port字段的顶级键,预期输出如下:
- service1 - service2 - service4
问题分析
使用命令 ./yq 'keys | .[] comments=""' file.yml 会返回所有顶级键(包括无port字段的service3),无法满足需求。
正确命令
使用to_entries配合select和map实现精准筛选:
./yq 'to_entries | map(select(.value | has("port")) | .key)' file.yml
命令解释
to_entries:将YAML的顶级键值对转换为[{key: "service1", value: {...}}, ...]格式的数组map(...):遍历数组中的每个元素select(.value | has("port")):筛选出value部分包含port字段的元素.key:提取筛选后元素的key值,最终得到符合要求的顶级键列表
内容的提问来源于stack exchange,提问作者maja
相关产品推荐
相关产品推荐

