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

如何用yq单命令行替换YAML值并保留原内容?

使用yq单命令批量修改YAML路径值

完全可以用单条yq命令实现需求,这里以主流的mikefarah/yq版本为例:

yq '(.. | select(has("paths"))).paths[] |= sub("~/", "~/base/1.0.0/")' input.yaml

命令解释:

  • ..:递归遍历YAML中的所有节点
  • select(has("paths")):筛选出包含paths键的节点
  • .paths[]:针对每个paths数组里的元素进行操作
  • |= sub("~/", "~/base/1.0.0/"):用字符串替换,把每个路径开头的~/替换成~/base/1.0.0/,保留后续原有内容

原YAML内容:

base:
- routes:
  - id: xxxxxx
    paths:
    - ~/\*$
  - id: xxxxxx
    paths:
    - ~/test$
- routes:
  - id: xxxxxx
    paths:
    - ~/number/{id}$
  - id: xxxxxx
    paths:
    - ~/anything$

修改后输出:

base:
- routes:
  - id: xxxxxx
    paths:
    - ~/base/1.0.0/\*$
  - id: xxxxxx
    paths:
    - ~/base/1.0.0/test$
- routes:
  - id: xxxxxx
    paths:
    - ~/base/1.0.0/number/{id}$
  - id: xxxxxx
    paths:
    - ~/base/1.0.0/anything$

如果需要直接修改原文件(而非输出到终端),添加-i参数:

yq -i '(.. | select(has("paths"))).paths[] |= sub("~/", "~/base/1.0.0/")' input.yaml

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 23:52:02