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

如何用mikefarah/yq提取含指定嵌套键的精简YAML文档

使用mikefarah/yq实现YAML结构化过滤

直接用这条yq命令就能得到你想要的结果:

yq '(.[] | .[] |= (map(select(.target-prop == "just-me") | {target-prop})))' input.yaml

命令拆解

  • 最外层的 .[]:遍历所有顶级命名空间(比如ns-a、ns-b)
  • .[] |= ...:对每个命名空间下的子节点(name-a、name-b)执行修改操作
  • map(...):遍历每个子节点下的数组元素
  • select(.target-prop == "just-me"):只保留target-prop值为just-me的数组项
  • {target-prop}:把筛选后的数组项精简,只保留target-prop字段

验证效果

输入YAML:

ns-a:
  name-a:
  -
    prop-a: "aye"
    prob-b:
      stuff: "that doesn't matter"
    target-prop: "just-me"
  -
    prop-a: "aye"
    target-prop: "not-me"
  name-b:
  -
    prop-a: "aye"
    target-prop: "just-me"
  -
    prop-a: "aye"
    prob-b:
      stuff: "that doesn't matter"
    target-prop: "not-me"
ns-b:
  name-a:
  -
    prop-a: "aye"
    target-prop: "just-me"
  -
    prop-a: "aye"
    prob-b:
      stuff: "that doesn't matter"
    target-prop: "not-me"
  name-b:
  -
    prop-a: "aye"
    target-prop: "just-me"
  -
    prop-a: "aye"
    prob-b:
      stuff: "that doesn't matter"
    target-prop: "not-me"

执行命令后输出:

ns-a:
  name-a:
    - target-prop: "just-me"
  name-b:
    - target-prop: "just-me"
ns-b:
  name-a:
    - target-prop: "just-me"
  name-b:
    - target-prop: "just-me"

这个结果完美匹配你的需求,还保留了YAML的数组层级标记-——这是ripgrep这类纯文本工具做不到的,因为它没法识别YAML的结构化层级,只能做行匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:43:10