mikefarah/yq

GitHub: mikefarah/yq

一款轻量级的命令行数据格式处理工具,支持使用类似 jq 的语法对 YAML、JSON、XML、CSV 等多种格式进行读取、修改、合并与转换。

Stars: 15142 | Forks: 754

# yq ![Build](https://static.pigsec.cn/wp-content/uploads/repos/2026/04/ff33dc138c090838.svg) ![Docker Pulls](https://img.shields.io/docker/pulls/mikefarah/yq.svg) ![Github Releases (by Release)](https://img.shields.io/github/downloads/mikefarah/yq/total.svg) ![Go Report](https://goreportcard.com/badge/github.com/mikefarah/yq) ![CodeQL](https://static.pigsec.cn/wp-content/uploads/repos/2026/04/4e1bc05ed9090840.svg) 一个轻量级且可移植的命令行 YAML、JSON、INI 和 XML 处理器。`yq` 使用类似 [jq](https://github.com/stedolan/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 ``` ### 高级操作 **合并多个文件:** ``` # 合并两个文件 yq -n 'load("file1.yaml") * load("file2.yaml")' # 使用 globs 合并(注意:`ea` 会一次性评估所有文件,而不是按顺序) 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 ``` **在数组中查找并更新项:** ``` # 注意:需要输入文件 - 在末尾添加你的文件 yq -i '(.[] | select(.name == "foo") | .address) = "12 cat st"' data.yaml ``` **在不同格式之间转换:** ``` # 将 JSON 转换为 YAML(pretty print) yq -Poy sample.json # 将 YAML 转换为 JSON yq -o json file.yaml # 将 XML 转换为 YAML yq -o yaml file.xml ``` 更多示例请参阅 [秘籍](https://mikefarah.gitbook.io/yq/recipes),获取更多信息请参阅 [文档](https://mikefarah.gitbook.io/yq/)。 请查看关于[常见问题](https://github.com/mikefarah/yq/discussions/categories/q-a)和[很酷的想法](https://github.com/mikefarah/yq/discussions/categories/show-and-tell)的讨论 ## 安装 ### [下载最新的二进制文件](https://github.com/mikefarah/yq/releases/latest) ### wget 使用 wget 下载预编译的二进制文件。选择您的平台和架构: **对于 Linux(示例):** ``` # 设置平台变量(根据需要调整) VERSION=v4.2.0 PLATFORM=linux_amd64 # 下载压缩二进制文件 wget https://github.com/mikefarah/yq/releases/download/${VERSION}/yq_${PLATFORM}.tar.gz -O - |\ tar xz && sudo mv yq_${PLATFORM} /usr/local/bin/yq # 或者下载普通二进制文件 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](https://brew.sh/) ``` brew install yq ``` ### 通过 snap 在 Linux 上安装: ``` snap install yq ``` #### Snap 说明 `yq` 在 snap 中安装时带有[_严格限制_](https://docs.snapcraft.io/snap-confinement/6233),这意味着它没有对 root 文件的直接访问权限。要读取 root 文件,您可以: ``` sudo cat /etc/myfile | yq '.a.path' ``` 要写入 root 文件,您可以使用 [sponge](https://linux.die.net/man/1/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 - 处理当前目录中的文件 docker run --rm -v "${PWD}":/workdir mikefarah/yq '.a.b[0].c' file.yaml # Podman - 用法与 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 管道传入数据: 您需要将 `-i --interactive` 标志传递给 Docker/Podman: ``` # 处理管道数据 docker run -i --rm mikefarah/yq '.this.thing' < myfile.yml # 与 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 Install: ``` go install github.com/mikefarah/yq/v4@latest ``` ## 社区支持的安装方式 这些由社区支持 :heart: —— 但是,它们可能未与官方支持的发行版保持同步。 _请注意,Debian 软件包(之前由 @rmescandon 支持)已不再维护。请使用其他安装方式。_ ### X-CMD 在 x-cmd 上查看 `yq`:https://x-cmd.com/mod/yq - 即时结果:实时查看您的 yq 过滤器输出。 - 错误处理:遇到语法错误?它将显示错误信息和最接近的有效过滤器的结果 感谢 @edwinjhlee! ### Nix ``` nix profile install nixpkgs#yq-go ``` 参见[这里](https://search.nixos.org/packages?channel=unstable&show=yq-go&from=0&size=50&sort=relevance&type=packages&query=yq-go) ### Webi ``` webi yq ``` 参见 [webi](https://webinstall.dev/) 由 @adithyasunil26 支持 (https://github.com/webinstall/webi-installers/tree/master/yq) ### Arch Linux ``` pacman -S go-yq ``` ### Windows: 使用 [Chocolatey](https://chocolatey.org) [![Chocolatey](https://img.shields.io/chocolatey/v/yq.svg)](https://chocolatey.org/packages/yq) [![Chocolatey](https://img.shields.io/chocolatey/dt/yq.svg)](https://chocolatey.org/packages/yq) ``` choco install yq ``` 由 @chillum 支持 (https://chocolatey.org/packages/yq) 使用 [scoop](https://scoop.sh/) ``` scoop install main/yq ``` 使用 [winget](https://learn.microsoft.com/en-us/windows/package-manager/) ``` winget install --id MikeFarah.yq ``` ### MacPorts: 使用 [MacPorts](https://www.macports.org/) ``` 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](https://github.com/marverix/gah) ``` gah install yq ``` ## 功能特性 - [包含大量示例的详细文档](https://mikefarah.gitbook.io/yq/) - 使用可移植的 go 语言编写,因此您可以下载一个可爱的无依赖二进制文件 - 使用类似 `jq` 的语法,但适用于 YAML、INI、[JSON](https://mikefarah.gitbook.io/yq/usage/convert) 和 [XML](https://mikefarah.gitbook.io/yq/usage/xml) 文件 - 完全支持多文档 yaml 文件 - 支持 yaml [front matter](https://mikefarah.gitbook.io/yq/usage/front-matter) 块(例如 jekyll/assemble) - 彩色 yaml 输出 - [带时区的日期/时间操作和格式化](https://mikefarah.gitbook.io/yq/operators/datetime) - [深层的数据结构](https://mikefarah.gitbook.io/yq/operators/traverse-read) - [键值排序](https://mikefarah.gitbook.io/yq/operators/sort-keys) - 操作 yaml [注释](https://mikefarah.gitbook.io/yq/operators/comment-operators)、[样式](https://mikefarah.gitbook.io/yq/operators/style)、[标签](https://mikefarah.gitbook.io/yq/operators/tag) 以及 [锚点和别名](https://mikefarah.gitbook.io/yq/operators/anchor-and-alias-operators)。 - [原地更新](https://mikefarah.gitbook.io/yq/v/v4.x/commands/evaluate#flags) - [用于选择和更新的复杂表达式](https://mikefarah.gitbook.io/yq/operators/select#select-and-update-matching-values-in-map) - 更新时保持 yaml 格式和注释(尽管存在空格问题) - [Decode/Encode base64 数据](https://mikefarah.gitbook.io/yq/operators/encode-decode) - [从其他文件加载内容](https://mikefarah.gitbook.io/yq/operators/load) - [与 json/ndjson 相互转换](https://mikefarah.gitbook.io/yq/v/v4.x/usage/convert) - [与 xml 相互转换](https://mikefarah.gitbook.io/yq/v/v4.x/usage/xml) - [与 hcl (terraform) 相互转换](https://mikefarah.gitbook.io/yq/v/v4.x/usage/hcl) - [与 toml 相互转换](https://mikefarah.gitbook.io/yq/v/v4.x/usage/toml) - [与 properties 相互转换](https://mikefarah.gitbook.io/yq/v/v4.x/usage/properties) - [与 csv/tsv 相互转换](https://mikefarah.gitbook.io/yq/usage/csv-tsv) - [通用的 shell 补全脚本 (bash/zsh/fish/powershell)](https://mikefarah.gitbook.io/yq/v/v4.x/commands/shell-completion) - [Reduce](https://mikefarah.gitbook.io/yq/operators/reduce) 以合并多个文件或对数组求和,以及执行其他奇妙的操作。 - [Github Action](https://mikefarah.gitbook.io/yq/usage/github-action),用于您的自动化流水线(感谢 @devorbitus) ## [使用方法](https://mikefarah.gitbook.io/yq/) 请查看 [文档](https://mikefarah.gitbook.io/yq/) 以获取更详细和高级的用法。 ``` Usage: yq [flags] yq [command] Examples: # yq 尝试根据扩展名自动检测文件格式,如果未知(或通过 STDIN 传输)则默认为 YAML # 使用 '-p/--input-format' 标志来指定格式类型。 cat file.xml | yq -p xml # 从 "myfile.yml" 中读取 "stuff" 节点 yq '.stuff' < myfile.yml # 原地更新 myfile.yml yq -i '.stuff = "foo"' myfile.yml # 将 sample.json 的内容以惯用 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. ) (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. ) (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. ) --xml-skip-proc-inst skip over process instructions (e.g. ) --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 引号问题:** ``` # 表达式使用单引号 yq '.a.b[0].c' file.yaml # 或者转义双引号 yq ".a.b[0].c = \"value\"" file.yaml ``` ### 获取帮助 - **查看现有 issues**:[GitHub Issues](https://github.com/mikefarah/yq/issues) - **提问**:[GitHub Discussions](https://github.com/mikefarah/yq/discussions) - **文档**:[完整文档](https://mikefarah.gitbook.io/yq/) - **示例**:[秘籍和示例](https://mikefarah.gitbook.io/yq/recipes) ## 已知问题 / 缺失功能 - `yq` 会尝试尽可能保留注释位置和空格,但并不能处理所有情况(详见 https://github.com/go-yaml/yaml/tree/v3) - Powershell 有它自己对 yq 引号的……[见解](https://mikefarah.gitbook.io/yq/usage/tips-and-tricks#quotes-in-windows-powershell) - "yes"、"no" 在 yaml 1.2 标准中已被移除作为布尔值——这是 yq 所遵循的标准。 有关更多常见问题和解决方案,请参阅[提示和技巧](https://mikefarah.gitbook.io/yq/usage/tips-and-tricks)。
标签:CSV处理器, EVTX分析, Go语言, HCL处理器, jq语法, JSON处理器, SEO工具, SOC Prime, TOML处理器, XML处理器, YAML处理器, 后端技术, 开发工具, 开源库, 搜索引擎爬虫, 文件格式转换, 文本处理, 文档结构分析, 日志审计, 流编辑器, 程序破解, 脚本编程, 运维工具, 配置文件管理