我正在尝试从csv文件生成一个hashmap
header1,header2,header3,header4
value1,val2,val3,val4
大约有一千行,我正在尝试生成 value1 header2“val2”header 3“val3”header4“val4”
答案 0 :(得分:0)
给出测试文件
header1,header2,header3,header4
value1,val2,val3,val4
a,b,c,d
我们可以做到
declare -A map
{
# read the first line
IFS=, read -ra headers
# iterate over the rest of the lines
while IFS=, read -ra values; do
# create the mapping
for i in "${!headers[@]}"; do
map["${headers[i]}"]=${values[i]}
done
# do something with the map
declare -p map
done
} < file.csv
输出
declare -A map='([header4]="val4" [header1]="value1" [header3]="val3" [header2]="val2" )'
declare -A map='([header4]="d" [header1]="a" [header3]="c" [header2]="b" )'
但这似乎是不必要的复杂。在headers
和values
数组之间建立公共索引可能就足够了。