yq - 通用结构化数据处理器
技能脚本入口
本技能附带两套等价包装脚本(Unix .sh + Windows PowerShell .ps1),提供友好子命令入口与安装自检,免去记忆原始参数。
macOS / Linux(bash):
bash scripts/yq-skill.sh <subcommand> [args...]
# 查看完整用法与示例
bash scripts/yq-skill.sh help
Windows(PowerShell):
.\scripts\yq-skill.ps1 <subcommand> [args...]
# 若被执行策略拦截,用下面这种调用绕过:
powershell -ExecutionPolicy Bypass -File scripts\yq-skill.ps1 <subcommand> [args...]
可用子命令: get、set、set-env、convert、merge、merge-all、format、csv-filter
脚本选择规则: macOS / Linux 用 .sh;Windows 用 .ps1。两者子命令完全一致。
> 脚本仅作便捷封装,最终调用系统的 yq 二进制;运行前请确保已安装对应工具(安装方式见下文各节)。说明:SkillHub 不支持 .cmd / .bat 文件类型,故不附带 Windows cmd 版;无 PowerShell 的环境可用 Git Bash 运行 .sh 版。个别依赖 Unix 管道工具的子命令(如 gron 的 sed / fzf)在 Windows 下建议用 Git Bash 运行 .sh 版。
这是什么
yq v4 (mikefarah/yq) 是一个轻量、可移植的命令行处理器,支持 YAML、JSON、XML、CSV、TSV、TOML、HCL、Properties、INI 等 10+ 格式。使用类 jq 语法,但能跨格式工作。单二进制文件 (Go),零依赖。
- GitHub: https://github.com/mikefarah/yq (15.9k ⭐)
- 文档: https://mikefarah.gitbook.io/yq/
- 支持多文档 YAML、前置元数据、注释保留、就地修改
何时使用我
当用户出现以下意图时加载此技能:
- "yq 命令"、"用 yq 处理 yaml/json"
- "yaml 转 json"、"json 转 yaml"、"xml 转 yaml"、"csv 转 json" 等格式转换
- "修改 yaml 配置文件"、"更新 config.yaml 中的值"
- "合并多个 yaml 文件"、"合并 kubernetes manifests"
- "提取 yaml/json/xml 中的特定字段"
- "就地修改配置文件"、
yq -i - "批量更新多个配置文件"
- "验证/格式化/排序 yaml"
- "处理 Helm values、K8s manifests、Docker Compose、GitHub Actions"
- "环境变量注入配置文件"
核心能力
1. 读取与查询 (jq 风格语法)
# 读取值(自动检测格式)
yq '.server.port' config.yaml
yq '.server.port' config.json
yq '.server.port' config.xml
# 从 stdin 读取
cat config.yaml | yq '.server.port'
# 多文档 YAML(用 --- 分隔)
yq 'select(.kind == "Deployment")' k8s-manifests.yaml
# 通配符与递归下降
yq '.. | select(has("replicas"))' k8s/*.yaml
2. 更新与修改 (就地修改 -i)
# 单值更新
yq -i '.server.port = 8080' config.yaml
# 多字段更新(管道链式)
yq -i '
.server.port = 8080 |
.database.host = "localhost" |
.feature_flags.new_ui = true
' config.yaml
# 使用环境变量
DB_PASSWORD=secret yq -i '.db.password = strenv(DB_PASSWORD)' config.yaml
# 数组操作:追加、插入、删除
yq -i '.servers += ["server3"]' config.yaml
yq -i 'del(.servers[0])' config.yaml
3. 格式转换 (核心优势)
# YAML -> JSON (美化输出 -P)
yq -P -o json config.yaml
# JSON -> YAML
yq -P -o yaml config.json
# XML -> YAML
yq -P -o yaml config.xml
# CSV -> JSON
yq -P -o json data.csv
# TOML -> YAML
yq -P -o yaml config.toml
# Properties -> YAML
yq -P -o yaml config.properties
# HCL (Terraform) -> YAML
yq -P -o yaml main.tf
# 指定输入格式 (自动检测通常足够)
yq -p xml -o yaml config.xml
4. 合并多文件
# 合并两个文件(后者覆盖前者)
yq -n 'load("base.yaml") * load("override.yaml")'
# 合并目录下所有 yaml(ea = eval-all,一次性加载所有文档)
yq -n 'ea . as $item ireduce ({}; . * $item)' configs/*.yaml
# 合并时保留数组不去重(用 append 而非 *)
yq -n 'load("a.yaml") *+ load("b.yaml")'
5. 复杂表达式与函数
# 条件更新
yq -i '(.deployments[] | select(.name == "web") | .replicas) = 5' k8s.yaml
# 遍历数组修改每个元素
yq -i '(.items[] | .status) = "active"' data.yaml
# 使用变量
yq -i '. as $root | .items[] | select(.id == $root.target_id)' data.yaml
# 日期时间操作
yq -i '.timestamp = now | .date = strftime("%Y-%m-%d")' data.yaml
# Base64 编解码
yq -i '.secret = @base64d' data.yaml
6. 前置元数据 处理
# 处理 Jekyll/Hugo 等前置元数据
yq -f front-matter=extract '.title' post.md
yq -f front-matter=process '.title = "New Title"' post.md
7. Shell 补全与交互
# 生成补全脚本
yq completion bash > /etc/bash_completion.d/yq
yq completion zsh > ~/.zsh/completions/_yq
yq completion fish > ~/.config/fish/completions/yq.fish
# 交互式模式(实验性)
yq --interactive
典型工作流示例
场景 1:Kubernetes Manifests 批量管理
# 1. 统一设置命名空间
yq -i '(.items[] | select(.kind == "Deployment") | .metadata.namespace) = "production"' *.yaml
# 2. 为所有 Deployment 添加标签
yq -i '(.items[] | select(.kind == "Deployment") | .metadata.labels.team) = "platform"' *.yaml
# 3. 修改镜像标签
yq -i '(.items[] | select(.kind == "Deployment") | .spec.template.spec.containers[].image) |= sub(":.*", ":v2.1.0")' *.yaml
# 4. 合并 base + overlay (Kustomize 替代方案)
yq -n 'load("base/deployment.yaml") * load("overlays/prod/deployment.yaml")' > deployment-prod.yaml
场景 2:Docker Compose 环境差异化
# 基础配置
# docker-compose.base.yml
# 覆盖配置
# docker-compose.prod.yml
yq -n 'load("docker-compose.base.yml") * load("docker-compose.prod.yml")' > docker-compose.yml
场景 3:CI/CD 配置动态生成
# GitHub Actions: 矩阵策略动态注入
VERSION=1.2.3 yq -i '.jobs.build.strategy.matrix.include += [{"version": strenv(VERSION), "os": "ubuntu-latest"}]' .github/workflows/ci.yml
# GitLab CI: 变量替换
yq -i '.variables.DOCKER_IMAGE = "registry.example.com/app:" + strenv(CI_COMMIT_TAG)' .gitlab-ci.yml
场景 4:配置文件标准化
# 1. 格式化并排序键
yq -i '.. style="" | sort_keys(..)' config.yaml
# 2. 统一缩进为 2 空格
yq -i -P -o yaml config.yaml
# 3. 移除空值
yq -i 'del(.. | select(. == null))' config.yaml
场景 5:CSV/Excel 数据快速处理
# CSV 转 JSON 数组
yq -P -o json data.csv
# CSV 过滤 (先转 JSON 再处理)
yq -p csv -o json data.csv | yq '(.[] | select(.status == "active"))'
# JSON 转 CSV
yq -o csv data.json
常用标志速查表
| 标志 | 说明 |
|---|---|
-i, --inplace |
就地修改文件 |
-P, --prettyPrint |
美化输出 (YAML 默认) |
-o, --output-format |
输出格式: yaml, json, xml, csv, tsv, toml, props, hcl, shell |
-p, --input-format |
强制输入格式 |
-n, --null-input |
不读输入,从头构建文档 |
-e, --exit-status |
无匹配时返回非零退出码 |
--colors / --no-colors |
强制开启/关闭颜色 |
-f, --front-matter |
处理前置元数据 |
-s, --split-exp |
将结果拆分到多文件 |
高级技巧
自定义函数库
# 定义函数文件 functions.yq
def trim: gsub("^\\s+|\\s+$", "");
# 使用
yq -L functions.yq '(.[] | .name |= trim)' data.yaml
GitHub Action 集成
# .github/workflows/update-config.yml
- name: Update version
uses: mikefarah/yq@master
with:
cmd: yq -i '.version = "${{ github.event.inputs.version }}"' config.yml
性能优化
# 大文件:禁用不需要的特性
yq --security-disable-env-ops --security-disable-file-ops '.key' huge.yaml
# 只读不写:移除文件操作权限
yq --security-disable-file-ops '.key' config.yaml
安装方式
# macOS (Homebrew)
brew install yq
# Linux (二进制)
wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yq
# Go 安装
go install github.com/mikefarah/yq/v4@latest
# Docker
docker run --rm -v "${PWD}":/workdir mikefarah/yq '.key' config.yaml
# Windows (Scoop/Chocolatey/Winget)
scoop install yq
choco install yq
winget install MikeFarah.yq
故障排查
| 问题 | 解决方案 |
|---|---|
| "command not found: yq" | 检查 PATH,或用 go install 重装 |
| 格式自动检测失败 | 显式指定 -p yaml -o json |
| 就地修改不生效 | 确保文件有写权限,检查 -i 参数位置 |
| 合并数组行为不符 | 用 *+ 追加、* 覆盖、= 完全替换 |
| XML 命名空间问题 | 加 --xml-keep-namespace 或 --xml-attribute-prefix |
| 注释丢失 | yq 尽力保留但不保证,重要注释建议单独管理 |
| 退出码异常 | 加 -e 让无匹配返回非零 |
版本差异注意
- v3 (Python) - 旧版,语法不同,已停止维护
- v4 (Go) - 当前主流,本技能基于 v4
- 检查版本:
yq --version应显示v4.x.x
相关技能
- fx - 交互式 TUI JSON 查看器(探索未知结构)
- dasel - 统一选择器语法操作 8+ 格式(语法更简洁)
- jq - 经典 JSON 处理器(纯 JSON 场景更快)
- rq - 10+ 格式互转(专注转换而非查询)
- miller - CSV/TSV/JSON 命名索引数据处理
- visidata - 终端电子表格(可视化分析)
技能版本: 1.0.0 | 作者: asdw741111 | 适用平台: OpenCode, Claude Code, Cursor, Codex CLI, Windsurf, Gemini CLI