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

如何用yq v4.28.1在YAML数组指定元素后插入新对象?

使用mikefarah/yq v4.28.1在指定YAML元素后插入新对象

可以实现这个需求,通过yq的insert结合index、select就能精准定位插入位置。

执行命令

假设你的YAML内容保存在input.yaml文件中,运行以下命令:

yq eval '.services |= insert((index(select(.name == "edgeview")) + 1), {"name": "new_element_name", "image": "new_element_image"})' input.yaml

命令说明

  • .services:定位到目标数组节点
  • index(select(.name == "edgeview")):找到name为edgeview的元素在数组中的索引
  • insert(pos, value):在索引+1的位置(即目标元素的下一位)插入指定的新对象

输入YAML

services:
  - name: newlogd
    image: NEWLOGD_TAG
    cgroupsPath: /eve/services/newlogd
    oomScoreAdj: -999
  - name: edgeview
    image: EDGEVIEW_TAG
    cgroupsPath: /eve/services/eve-edgeview
    oomScoreAdj: -800
  - name: debug
    image: DEBUG_TAG
    cgroupsPath: /eve/services/debug
    oomScoreAdj: -999
  - name: wwan
    image: WWAN_TAG
    cgroupsPath: /eve/services/wwan
    oomScoreAdj: -999

输出YAML

services:
  - name: newlogd
    image: NEWLOGD_TAG
    cgroupsPath: /eve/services/newlogd
    oomScoreAdj: -999
  - name: edgeview
    image: EDGEVIEW_TAG
    cgroupsPath: /eve/services/eve-edgeview
    oomScoreAdj: -800
  - name: new_element_name
    image: new_element_image
  - name: debug
    image: DEBUG_TAG
    cgroupsPath: /eve/services/debug
    oomScoreAdj: -999
  - name: wwan
    image: WWAN_TAG
    cgroupsPath: /eve/services/wwan
    oomScoreAdj: -999

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:15:21