You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bash结合yq读取YAML生成关联数组并遍历打印

需求描述

借助mikefarah仓库的yq工具,遍历data.yaml中的各个state节点,捕获每个state下的键值对,为每个state创建Bash关联数组,最后打印数组内容。

数据文件:data.yaml

data:
  continent:
    countries:
      - state1:
          capital1: city1
          capital2: city2
      - state2:
          capital2: city2
      - state3:
          capital3: city3
      - state4:
          capital4: city4
          capital5: city5

预期输出

echo state1[@]
key capital1, value city1
key capital2, value city2

echo state2[@]
key capital2, value city2

echo state3[@]
key capital3, value city3

echo state4[@]
key capital4, value city4
key capital5, value city5

用户尝试的失败方案

Try1

#!/bin/bash

declare -A state1_list

while IFS="=" read -r key value; do state1_list["$key"]=$value; done < <(
  yq '.mft.aw-dev.components[].state1 | to_entries | map([.key, .value] | join("=")) | .[]' data.yaml
)

for key in "${!state1_list[@]}"; do printf "key %s, value %s\n" "$key" "${state1_list[$key]}"; done 

问题:路径错误(使用了不存在的.mft.aw-dev.components[]),且仅处理单个state1,未遍历所有state节点。

Try2

for i in $(yq '.data.continent.countries[] | keys' data.yaml| sed -e 's/-//g' | sed '/^$/d'); do echo -- $i --; yq '.mft.aw-dev.components[].$i.state[]' data.yaml; done
# (For iterating and then finding values)

问题:路径错误,yq中引用Bash变量的方式不正确,且未正确提取state下的键值对数据。

解决方案

以下是可以实现需求的Bash脚本:

#!/bin/bash

# 提取所有state节点名称
states=$(yq '.data.continent.countries[] | keys | .[]' data.yaml)

for state in $states; do
    # 动态声明关联数组
    declare -A "${state}_list"
    
    # 用yq提取当前state的键值对,格式化为key=value后读取到数组中
    while IFS="=" read -r key value; do
        eval "${state}_list[$key]=\"$value\""
    done < <(yq ".data.continent.countries[] | select(has(\"$state\")) | .\"$state\" | to_entries | map([.key, .value] | join(\"=\")) | .[]" data.yaml)
    
    # 打印数组信息
    echo "echo ${state}[@]"
    for key in "${!${state}_list[@]}"; do
        printf "key %s, value %s\n" "$key" "${${state}_list[$key]}"
    done
    echo ""
done

关键说明

  1. 提取state名称:通过yq '.data.continent.countries[] | keys | .[]'获取所有state节点的名称,如state1、state2等。
  2. 动态创建数组:使用declare -A "${state}_list"根据state名称动态生成关联数组。
  3. 提取键值对:用select(has("$state"))筛选出当前state的节点,再通过to_entries将键值对转为数组,最后拼接成key=value格式。
  4. 数组赋值与打印:借助eval处理动态数组的赋值,遍历数组键名打印所有键值对。

内容的提问来源于stack exchange,提问作者jagatjyoti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:32:23