mcpField
Y
yq

yq

公式おすすめAgent-ready
github.comデータベース・データ16.2kyq1 日前に更新
リポジトリ公式サイト

yq について

yq は構造化データを扱うコマンドラインツールで、コマンドは yq です。式で設定ファイルの内容を取り出せ、ファイルの直接更新にも対応し、入出力はパイプラインに組み込みやすいです。

主な機能

  1. 01yq ".services" compose.yml で特定の項目を抽出
  2. 02-i でその場で更新(例: yq -i ".version = 2" config.yml)
  3. 03パイプラインに向いた入出力
  4. 04繰り返し実行できるデータ処理

活用シーン

  1. 01CI スクリプトで設定のバージョン番号を更新
  2. 02compose.yml の一部だけを確認
  3. 03コーディングエージェントが他の部分に触れず設定を的確に変更

インストール

OS またはパッケージマネージャーを選び、コマンドをターミナルで実行します。

$
brew install yq

インストール後にyq --versionを実行して確認します。

コマンド例

よく使うコマンドを使う順に並べています。

01
yq ".services" compose.yml
02
yq -i ".version = 2" config.yml

詳細

yq

Build Docker Pulls Github Releases (by Release) Go Report CodeQL

軽量でポータブルな、YAML、JSON、INI、XML 用のコマンドラインプロセッサーです。yq は、人気の JSON プロセッサーである jq のような構文を使用し、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 に関する注意事項

snap では yq は厳格なコンフィネーションでインストールされるため、root ファイルに直接アクセスできません。root ファイルを読み取るには、次のようにします。

sudo cat /etc/myfile | yq '.a.path'

root ファイルに書き込むには、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

Docker コマンド全体を入力する手間を省くために、bash 関数を用意しておくと便利です。

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
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)。

コミュニティによってサポートされているインストール方法

コミュニティがサポートしています :heart:。ただし、公式にサポートされているリリースより古い場合があります。

以前は @rmescandon によってサポートされていた Debian パッケージは、現在メンテナンスされていません。別のインストール方法をご利用ください。

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 を使用

Chocolatey 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 を使用すると、WSL 経由で Linux、MacOS、Windows に yq をインストールできます。

flox install yq
gah 経由の MacOS / Linux:

gah を使用

gah install yq

機能

使い方

より詳細で高度な使い方については、ドキュメントをご覧ください。

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
ヘルプの利用

既知の問題/未実装の機能

  • yq はコメントの位置と空白をできるだけ保持しようとしますが、すべてのケースには対応していません(詳細については https://github.com/go-yaml/yaml/tree/v3 を参照してください)
  • PowerShell には、yq の引用符の扱いに関する独自の……見解があります
  • YAML 1.2 標準(yq が前提とする標準)では、「yes」と「no」はブール値として扱われなくなりました。

よくある問題と解決策については、ヒントとコツをご覧ください。

コメント