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

使用yq拆分大型游戏YAML文件时遇单引号语法错误求助

解决yq拆分YAML数组为单个文件的语法问题

问题场景

你有一个存储游戏信息的YAML文件GameCollection.yaml,内容如下:

---
-
    Name: Metal Gear Solid HD Collection
    Console: PS3
    Genre: Stealth 
    Progression: Unplayed
    Maintenance: Perfect!
-
    Name: Metal Gear Solid 4 Guns of the Patriots
    Console: PS3
    Genre: Stealth 
    Progression: Unplayed
    Maintenance: Perfect!
-
    Name: Metal Gear Rising Revengeance
    Console: PS3
    Genre: Power Fantasy
    Progression: Compleat (Blade Wold DLC to play)
    Maintenance: Perfect!
-

需要将每个游戏条目拆分到单独文件,文件名包含游戏名和索引以避免重名,但多次尝试yq命令均报错,比如:

  • yq e GameCollection.yaml -s .Name 报错cannot index array with 'Name'
  • yq e GameCollection.yaml -s '.Name' 报错bad split document expression

正确解决方案

针对mikefarah/yq v4.x(当前主流版本),使用以下命令即可完成拆分:

# 基础版本:拆分所有条目(包括空条目)
yq e -s '.Name + "_" + ($index | tostring)' GameCollection.yaml

# 优化版本:过滤掉末尾的空条目,只处理有Name的游戏
yq e -s 'select(.Name != null) | .Name + "_" + ($index | tostring)' GameCollection.yaml

执行后会生成如下文件:

  • Metal Gear Solid HD Collection_0.yaml
  • Metal Gear Solid 4 Guns of the Patriots_1.yaml
  • Metal Gear Rising Revengeance_2.yaml

错误原因解析

之前的命令主要犯了两个关键错误:

  1. 参数顺序颠倒:yq的-s(拆分)选项需要紧跟在表达式参数e之后,放在表达式前面,而不是文件名后面。正确的参数结构是:yq e [选项] [表达式] [文件名],而非yq e [文件名] [选项] [表达式]。
  2. Shell引号与表达式处理不当:
    • 拆分表达式需要用单引号完整包裹,避免shell解析其中的+、$index等符号,确保表达式完整传递给yq。
    • $index是数字类型,必须用tostring转换为字符串后才能和文本拼接,否则会触发类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 04:46:12