bash - 如何从 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
我怎样才能做到这一点?
解决方案
在同一内容上多次使用 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[*]}"
推荐阅读
- r - 有没有办法让我的柱状图中的数字出现在我的直方图中?
- c++ - 将 char* 转换为字符串?
- javascript - vue和electron共享一个store
- bash - 从 Debian Buster VM 上的另一个 bash 脚本中调用 Bash 脚本
- terraform - 使用 terraform 创建 GCP VM 时如何使用图像或快照?
- python - PySpark Databricks 使用增量合并时如何仅获取更改的行以匹配条件
- php - 过滤并匹配 TYPEFORM 数组答案 ID 到问题 ID PHP
- html - 如何在html中向右移动按钮
- asp.net-core - 实现外观模式在 .Net Core 5 MVC 中不起作用
- r - 通过在 R 中交替其值来对向量进行排序