首页 > 解决方案 > 如何从 Bash 中的两个数组构建关联数组?

问题描述

我有两个数组,我想将它们创建为键/值对,即用它们构建一个关联数组。

这是我的代码:

#!/bin/bash

a=$(awk -F{ '{print $1}' test.txt) #output:  [Sun Mon Tues Wed Thu Fri Sat]
b=$(awk -F "[{}]" '{print $2}' test.txt)  #output:  [03:00 05:00 07:00 03:00 05:00 07:00 07:00]

declare -A arr
for j in $b
do
    time=$j
    for k in $a; do
        days=$k
        arr["$days"]=$time
    done
done

echo ${arr[@]} # o/p: 07:00 07:00 07:00 07:00 07:00 07:00 07:00

我得到这个输出:

"07:00 07:00 07:00 07:00 07:00 07:00 07:00"

但我期待

03:00 05:00 07:00 03:00 05:00 07:00 07:00

我怎样才能做到这一点?

标签: bashassociative-array

解决方案


在同一内容上多次使用 awk 通常是个坏主意,而且 bash shell 内置了对读取分隔字段的支持。以下是处理文件以填充数组的方法:

#!/usr/bin/env bash

declare -A arr

# Iterate reading fields delimited by any of [{}] into k v variables
while IFS='[{}]' read -r k v; do
  arr["$k"]="$v" # Populate associative array
done <test.txt # from this file

# Print joined values from arr formatted inside brackets
printf '[%s]\n' "${arr[*]}"

推荐阅读