You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:50:04