0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

yq v4 を使って YAML から値を取得したり、値を挿入した時のメモ

Posted at

yq v4 を使って YAML から値を取得したり、値を挿入した時のメモ

環境

$yq --version
yq (https://github.com/mikefarah/yq/) version 4.27.5

インストール は Mac を使っているので brew install yq でインストールした

v3 と v4 は使い方がかなり変わっているようで以下に差異がまとまっているので注意

Upgrading from V3

自分は最新の v4 で検証した

使ってみる

以下を見ながら使う

Quick Usage Guide

Read a value

以下のような YAML があるとする

test.yaml
Samples:
- name: satoshi
  topics: CV Debuted
- name: tsumoto
  nickname: gyopa-

上記から satoshi を取得したい場合、以下のように記述する

yq '.Samples[0].name' test.yaml

Update a yaml file, inplace

先ほどの satoshi という名前を ryoma に変えてみる

yq '.Samples[0].name = "ryoma"' test.yaml
Samples:
  - name: ryoma
    topics: CV Debuted
  - name: tsumoto
    nickname: gyopa-

OK

-i オプションを使えば、ファイルの上書きする(-i なしの場合、test.yaml は変更なし)

yq -i '.Samples[0].name = "ryoma"' test.yaml

cat test.yaml
Samples:
  - name: ryoma
    topics: CV Debuted
  - name: tsumoto
    nickname: gyopa-

Update using environment variables

先ほどの例では固定の名称を指定していたが、環境変数を利用したい場合、strenv を使う

# NAME という環境変数に mike を指定
export NAME=mike

# 確認
echo $NAME
mike

# 環境変数を使って変更
yq '.Samples[0].name = strenv(NAME)' test.yaml
Samples:
  - name: mike
    topics: CV Debuted
  - name: tsumoto
    nickname: gyopa-

追加する

YAML の特定箇所に値を追加する場合、挿入箇所を指定して値を設定すれば OK

yq '.Samples[0].year = "2022"' test.yaml
Samples:
  - name: ryoma
    topics: CV Debuted
    year: "2022"
  - name: tsumoto
    nickname: gyopa-

実行したコマンドの結果を入れる場合、strenv を使って以下のようにすれば OK

DATE=`date` yq '.Samples[0].date = strenv(DATE)' test.yaml
Samples:
  - name: ryoma
    topics: CV Debuted
    date: Sun Sep 25 06:24:44 JST 2022
  - name: tsumoto
    nickname: gyopa-
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?