关于 yq
yq 是处理结构化数据的命令行工具,命令为 yq。可用表达式查询配置文件中的内容,也能原地修改,输入输出适合接入管道。
主要功能
- 01用 yq ".services" compose.yml 提取指定字段
- 02用 -i 原地修改文件,如 yq -i ".version = 2" config.yml
- 03适合管道的输入与输出
- 04可重复执行的数据处理
适用场景
- 01在 CI 脚本中批量更新配置版本号
- 02查看 compose.yml 中的某一部分
- 03编码 Agent 精确修改配置而不改动其他内容
安装
选择你的系统或包管理器,复制命令到终端运行。
安装完成后运行yq --version确认安装成功。
命令示例
常用命令按使用顺序排列。
详细介绍
yq
一款轻量、便携的命令行 YAML、JSON、INI 和 XML 处理器。yq 使用类似 jq(一款流行的 JSON 处理器)的语法,同时也支持 YAML 文件,以及 JSON、kyaml、XML、INI、properties、CSV 和 TSV。它尚未支持 jq 的所有功能,但支持最常用的操作和函数,并在持续添加更多功能。
yq 使用 Go 编写,因此你可以下载适用于自己平台的免依赖二进制文件,即可开始使用!如果你愿意,也可以使用下方列出的各种包管理器,以及 Docker 和 Podman。
快速使用指南
基本操作
读取一个值:
yq '.a.b[0].c' file.yaml
从 STDIN 管道传入:
yq '.a.b[0].c' < file.yaml
就地更新 YAML 文件:
yq -i '.a.b[0].c = "cool"' file.yaml
使用环境变量更新:
NAME=mike yq -i '.a.b[0].c = strenv(NAME)' file.yaml
高级操作
合并多个文件:
# merge two files
yq -n 'load("file1.yaml") * load("file2.yaml")'
# merge using globs (note: `ea` evaluates all files at once instead of in sequence)
yq ea '. as $item ireduce ({}; . * $item )' path/to/*.yml
多次更新 YAML 文件:
yq -i '
.a.b[0].c = "cool" |
.x.y.z = "foobar" |
.person.name = strenv(NAME)
' file.yaml
查找并更新数组中的项目:
# Note: requires input file - add your file at the end
yq -i '(.[] | select(.name == "foo") | .address) = "12 cat st"' data.yaml
在不同格式之间转换:
# Convert JSON to YAML (pretty print)
yq -Poy sample.json
# Convert YAML to JSON
yq -o json file.yaml
# Convert XML to YAML
yq -o yaml file.xml
安装
下载最新二进制文件
wget
使用 wget 下载预编译的二进制文件。选择你的平台和架构:
适用于 Linux(示例):
# Set your platform variables (adjust as needed)
VERSION=v4.2.0
PLATFORM=linux_amd64
# Download compressed binary
wget https://github.com/mikefarah/yq/releases/download/${VERSION}/yq_${PLATFORM}.tar.gz -O - |\
tar xz && sudo mv yq_${PLATFORM} /usr/local/bin/yq
# Or download plain binary
wget https://github.com/mikefarah/yq/releases/download/${VERSION}/yq_${PLATFORM} -O /usr/local/bin/yq &&\
chmod +x /usr/local/bin/yq
最新版本(Linux AMD64):
wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq &&\
chmod +x /usr/local/bin/yq
可用平台: linux_amd64、linux_arm64、linux_arm、linux_386、darwin_amd64、darwin_arm64、windows_amd64、windows_386 等。
通过 Homebrew 安装 MacOS / Linux:
使用 Homebrew
brew install yq
通过 snap 安装 Linux 版:
snap install yq
Snap 说明
yq 在 snap 中以严格限制模式安装,这意味着它无法直接访问根目录下的文件。若要读取根目录下的文件,可以:
sudo cat /etc/myfile | yq '.a.path'
若要写入根目录下的文件,可以使用 sponge:
sudo cat /etc/myfile | yq '.a.path = "value"' | sudo sponge /etc/myfile
也可以写入临时文件:
sudo cat /etc/myfile | yq '.a.path = "value"' | sudo tee /etc/myfile.tmp
sudo mv /etc/myfile.tmp /etc/myfile
rm /etc/myfile.tmp
使用 Docker 或 Podman 运行
一次性使用:
# Docker - process files in current directory
docker run --rm -v "${PWD}":/workdir mikefarah/yq '.a.b[0].c' file.yaml
# Podman - same usage as Docker
podman run --rm -v "${PWD}":/workdir mikefarah/yq '.a.b[0].c' file.yaml
**安全说明:**你可以在 Docker 中以受限权限运行 yq:
docker run --rm --security-opt=no-new-privileges --cap-drop all --network none \
-v "${PWD}":/workdir mikefarah/yq '.a.b[0].c' file.yaml
通过 STDIN 管道传入数据:
你需要为 Docker/Podman 传入 -i --interactive 标志:
# Process piped data
docker run -i --rm mikefarah/yq '.this.thing' < myfile.yml
# Same with Podman
podman run -i --rm mikefarah/yq '.this.thing' < myfile.yml
交互式运行命令:
docker run --rm -it -v "${PWD}":/workdir --entrypoint sh mikefarah/yq
podman run --rm -it -v "${PWD}":/workdir --entrypoint sh mikefarah/yq
你可以创建一个 bash 函数,避免每次输入完整的 docker 命令:
yq() {
docker run --rm -i -v "${PWD}":/workdir mikefarah/yq "$@"
}
yq() {
podman run --rm -i -v "${PWD}":/workdir mikefarah/yq "$@"
}
以 root 身份运行:
yq 的容器镜像不再以 root 身份运行(https://github.com/mikefarah/yq/pull/860)。如果你想在容器镜像中安装更多内容,或者读取/写入文件时遇到权限问题,则需要:
docker run --user="root" -it --entrypoint sh mikefarah/yq
podman run --user="root" -it --entrypoint sh mikefarah/yq
或者,在你的 Dockerfile 中:
FROM mikefarah/yq
USER root
RUN apk add --no-cache bash
USER yq
缺少时区数据
默认情况下,yq 使用的 alpine 镜像不包含时区数据。如果你想使用 tz 运算符,需要添加这些数据:
FROM mikefarah/yq
USER root
RUN apk add --no-cache tzdata
USER yq
使用 SELinux 的 Podman
如果你使用启用了 SELinux 的 podman,需要在卷挂载上设置共享卷标志 :z:
-v "${PWD}":/workdir:z
GitHub Action
- name: Set foobar to cool
uses: mikefarah/yq@master
with:
cmd: yq -i '.foo.bar = "cool"' 'config.yml'
- name: Get an entry with a variable that might contain dots or spaces
id: get_username
uses: mikefarah/yq@master
with:
cmd: yq '.all.children.["${{ matrix.ip_address }}"].username' ops/inventories/production.yml
- name: Reuse a variable obtained in another step
run: echo ${{ steps.get_username.outputs.result }}
更多信息请参阅 https://mikefarah.gitbook.io/yq/usage/github-action。
Go 安装:
go install github.com/mikefarah/yq/v4@latest
将 yq 用作 Go 库
上面的命令会安装 yq CLI。若要在 Go 程序中使用 yq,请通过 go get github.com/mikefarah/yq/v4 将其添加到 Go 模块,并导入 github.com/mikefarah/yq/v4/pkg/yqlib。
请参阅 examples/library/main.go,其中提供了一个简单、可运行的示例(go run ./examples/library)。
社区支持的安装方式
这些安装方式由社区 ❤️ 支持,但可能未及时更新到官方支持的版本。
请注意,Debian 软件包(此前由 @rmescandon 提供支持)已不再维护。请改用其他安装方式。
X-CMD
在 x-cmd 上查看 yq:https://x-cmd.com/mod/yq
- 即时结果:实时查看 yq 筛选器的输出。
- 错误处理:遇到语法错误?它会显示错误消息,以及最接近的有效筛选器的结果。
感谢 @edwinjhlee!
Nix
nix profile install nixpkgs#yq-go
请参阅此处
Webi
webi yq
请参阅 webi 由 @adithyasunil26 提供支持 (https://github.com/webinstall/webi-installers/tree/master/yq)
Arch Linux
pacman -S go-yq
Windows:
使用 Chocolatey
choco install yq
由 @chillum 提供支持 (https://chocolatey.org/packages/yq)
使用 scoop
scoop install main/yq
使用 winget
winget install --id MikeFarah.yq
MacPorts:
使用 MacPorts
sudo port selfupdate
sudo port install yq
由 @herbygillot 提供支持 (https://ports.macports.org/maintainer/github/herbygillot)
Alpine Linux
Alpine Linux v3.20+(以及 Edge):
apk add yq-go
Alpine Linux v3.19 及更早版本:
apk add yq
由 Tuan Hoang 提供支持 (https://pkgs.alpinelinux.org/packages?name=yq-go)
Flox:
可通过 Flox 在 Linux、MacOS 和 Windows(通过 WSL)上安装 yq。
flox install yq
通过 gah 在 MacOS / Linux 上安装:
使用 gah
gah install yq
功能
- 包含大量示例的详细文档
- 使用便携式 Go 编写,因此你可以下载一个轻巧且无需依赖的二进制文件
- 使用与
jq类似的语法,但适用于 YAML、INI、JSON 和 XML 文件 - 完全支持多文档 YAML 文件
- 支持 YAML 前置内容块(例如 Jekyll/assemble)
- 彩色 YAML 输出
- 使用 TZ 操作和格式化日期/时间
- 深层数据结构
- 排序键
- 操作 YAML 注释、样式、标签以及锚点和别名。
- 原地更新
- 使用复杂表达式进行选择和更新
- 更新时保留 YAML 格式和注释(但空白字符处理仍存在问题)
- 解码/编码 Base64 数据
- 从其他文件加载内容
- 转换为/从 JSON/NDJSON 转换
- 转换为/从 XML 转换
- 转换为/从 HCL(Terraform)转换
- 转换为/从 TOML 转换
- 转换为/从 properties 转换
- 转换为/从 CSV/TSV 转换
- 通用 Shell 补全脚本(bash/zsh/fish/powershell)
- Reduce,可用于合并多个文件、对数组求和,以及完成其他复杂操作。
- GitHub Action,可用于自动化流水线(感谢 @devorbitus)
用法
如需了解更详细和高级的用法,请查看文档。
Usage:
yq [flags]
yq [command]
Examples:
# yq tries to auto-detect the file format based off the extension, and defaults to YAML if it's unknown (or piping through STDIN)
# Use the '-p/--input-format' flag to specify a format type.
cat file.xml | yq -p xml
# read the "stuff" node from "myfile.yml"
yq '.stuff' < myfile.yml
# update myfile.yml in place
yq -i '.stuff = "foo"' myfile.yml
# print contents of sample.json as idiomatic YAML
yq -P -oy sample.json
Available Commands:
completion Generate the autocompletion script for the specified shell
eval (default) Apply the expression to each document in each yaml file in sequence
eval-all Loads _all_ yaml documents of _all_ yaml files and runs expression once
help Help about any command
Flags:
-C, --colors force print with colors
--csv-auto-parse parse CSV YAML/JSON values (default true)
--csv-separator char CSV Separator character (default ,)
--debug-node-info debug node info
-e, --exit-status set exit status if there are no matches or null or false is returned
--expression string forcibly set the expression argument. Useful when yq argument detection thinks your expression is a file.
--from-file string Load expression from specified file.
-f, --front-matter string (extract|process) first input as yaml front-matter. Extract will pull out the yaml content, process will run the expression against the yaml content, leaving the remaining data intact
--header-preprocess Slurp any header comments and separators before processing expression. (default true)
-h, --help help for yq
-I, --indent int sets indent level for output (default 2)
-i, --inplace update the file in place of first file given.
-p, --input-format string [auto|a|yaml|y|json|j|kyaml|ky|props|p|csv|c|tsv|t|xml|x|base64|uri|toml|hcl|h|lua|l|ini|i] parse format for input. (default "auto")
--lua-globals output keys as top-level global variables
--lua-prefix string prefix (default "return ")
--lua-suffix string suffix (default ";\n")
--lua-unquoted output unquoted string keys (e.g. {foo="bar"})
-M, --no-colors force print with no colors
-N, --no-doc Don't print document separators (---)
-0, --nul-output Use NUL char to separate values. If unwrap scalar is also set, fail if unwrapped scalar contains NUL char.
-n, --null-input Don't read input, simply evaluate the expression given. Useful for creating docs from scratch.
-o, --output-format string [auto|a|yaml|y|json|j|kyaml|ky|props|p|csv|c|tsv|t|xml|x|base64|uri|toml|hcl|h|shell|s|lua|l|ini|i] output format type. (default "auto")
-P, --prettyPrint pretty print, shorthand for '... style = ""'
--properties-array-brackets use [x] in array paths (e.g. for SpringBoot)
--properties-separator string separator to use between keys and values (default " = ")
--security-disable-env-ops Disable env related operations.
--security-disable-file-ops Disable file related operations (e.g. load)
--shell-key-separator string separator for shell variable key paths (default "_")
-s, --split-exp string print each result (or doc) into a file named (exp). [exp] argument must return a string. You can use $index in the expression as the result counter. The necessary directories will be created.
--split-exp-file string Use a file to specify the split-exp expression.
--string-interpolation Toggles strings interpolation of \(exp) (default true)
--tsv-auto-parse parse TSV YAML/JSON values (default true)
-r, --unwrapScalar unwrap scalar, print the value with no quotes, colors or comments. Defaults to true for yaml (default true)
-v, --verbose verbose mode
-V, --version Print version information and quit
--xml-attribute-prefix string prefix for xml attributes (default "+@")
--xml-content-name string name for xml content (if no attribute name is present). (default "+content")
--xml-directive-name string name for xml directives (e.g. <!DOCTYPE thing cat>) (default "+directive")
--xml-keep-namespace enables keeping namespace after parsing attributes (default true)
--xml-proc-inst-prefix string prefix for xml processing instructions (e.g. <?xml version="1"?>) (default "+p_")
--xml-raw-token enables using RawToken method instead Token. Commonly disables namespace translations. See https://pkg.go.dev/encoding/xml#Decoder.RawToken for details. (default true)
--xml-skip-directives skip over directives (e.g. <!DOCTYPE thing cat>)
--xml-skip-proc-inst skip over process instructions (e.g. <?xml version="1"?>)
--xml-strict-mode enables strict parsing of XML. See https://pkg.go.dev/encoding/xml for more details.
--yaml-fix-merge-anchor-to-spec Fix merge anchor to match YAML spec. Will default to true in late 2025
Use "yq [command] --help" for more information about a command.
故障排除
常见问题
PowerShell 引号问题:
# Use single quotes for expressions
yq '.a.b[0].c' file.yaml
# Or escape double quotes
yq ".a.b[0].c = \"value\"" file.yaml
获取帮助
- 查看现有问题:GitHub Issues
- 提问:GitHub Discussions
- 文档:完整文档
- 示例:使用技巧和示例
已知问题 / 缺失功能
yq会尽可能保留注释位置和空白字符,但无法处理所有情况(详情请参见 https://github.com/go-yaml/yaml/tree/v3)- Powershell 对如何为 yq 使用引号有自己的……看法
- 在 YAML 1.2 标准中,"yes"、"no" 不再作为布尔值,而 yq 默认使用该标准。
更多常见问题和解决方案,请参阅使用技巧。