如何用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
相关产品推荐
相关产品推荐

