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

Yaml YQ使用[]迭代筛选用例时如何保留迭代对应的组件键信息

yq筛选嵌套YAML指定项并保留上层层级的实现方法

问题原因

之前执行的命令丢失上层组件信息,是因为写法直接通过管道下钻到了tests数组层级,输出时上下文已经脱离了外层的component键结构,最终只会返回所有匹配到的测试用例平铺列表。

正确命令

使用更新运算符|=替代直接管道取值,在保留外层原始结构的前提下,对每个组件下的tests数组做过滤即可,命令如下:

yq e '.[].tests |= map(select(.type == "automated"))' file.yaml -P

命令说明

  • |=是yq的更新赋值运算符,不会切换当前上下文的根结构,只会对左侧匹配到的节点,用右侧表达式的计算结果原地替换
  • 上述命令会遍历所有顶层组件键,对每个组件下的tests数组执行过滤,仅保留type为automated的用例,外层组件结构会完整保留
  • 执行后的输出和期望格式完全一致:
component1:
  tests:
    - name: test2
      type: automated
    - name: test4
      type: automated
    - name: test6
      type: automated
component2:
  tests:
    - name: test2
      type: automated
    - name: test4
      type: automated
    - name: test6
      type: automated

可选输出形式

如果需要其他分组展示形式,比如直接输出组件名和对应自动化用例的扁平映射,也可以使用如下命令:

yq e 'to_entries | map({.key: (.value.tests | map(select(.type == "automated")))}) | add' file.yaml -P

内容的提问来源于stack exchange,提问作者Kris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:54:34