LoginSignup
1
0

More than 1 year has passed since last update.

yqコマンドでyamlのリストをループ処理したい

Last updated at Posted at 2022-07-03

背景

yamlファイルを処理するyqというコマンドがある。これを使ってyamlのリストをループ処理したい場面があったのでその方法を書いておく。

やりかた

以下のようなyamlファイル(sample.yml)があったとする。コメントがあっても問題ない。

- name: taro
  age: 20

# 次男だよ
- name: jiro
  age: 18

- name: pochi
  age: 3

この各要素に対して何らかの処理をしたい場合、以下のようにできる。

num=$(yq '. | length' sample.yml)
for i in $(seq 0 $(($num-1))); do
    name=$(yq ".[$i].name" sample.yml)
    age=$(yq ".[$i].age" sample.yml)
  
    echo "${name} is ${age} years old."
done

うまくループ処理できている。

taro is 20 years old.
jiro is 18 years old.
pochi is 3 years old.
1
0
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
1
0