Bash 从文件读取到关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23442173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash reading from a file to an associative array
提问by user3598639
I'm trying to write a script in bash using an associative array.
I have a file called data
:
我正在尝试使用关联数组在 bash 中编写脚本。我有一个名为data
:
a,b,c,d,e,f
g,h,i,j,k,l
The following script:
以下脚本:
oldIFS=${IFS}
IFS=","
declare -A assoc
while read -a array
do
assoc["${array[0]}"]="${array[@]"
done
for key in ${!assoc[@]}
do
echo "${key} ---> ${assoc[${key}]}"
done
IFS=${oldIFS}
gives me
给我
a ---> a b c d e f
g ---> g h i j k l
I need my output to be:
我需要我的输出是:
a b ---> c d e f
g h ---> i j k l
回答by Ashkan
oldIFS=${IFS}
IFS=","
declare -A assoc
while read -r -a array
do
assoc["${array[0]} ${array[1]}"]="${array[@]:2}"
done < data
for key in "${!assoc[@]}"
do
echo "${key} ---> ${assoc[${key}]}"
done
IFS=${oldIFS}
data:
数据:
a,b,c,d,e,f
g,h,i,j,k,l
Output:
输出:
a b ---> c d e f
g h ---> i j k l
Uses Substring Expansion
here ${array[@]:2}
to get substring needed as the value of the assoc
array. Also added -r
to read
to prevent backslash to act as an escape character.
Substring Expansion
在此处使用${array[@]:2}
以获取作为assoc
数组值所需的子字符串。还添加-r
到read
以防止反斜杠充当转义字符。
Improved based on @gniourf_gniourf's suggestions:
根据@gniourf_gniourf 的建议改进:
declare -A assoc
while IFS=, read -r -a array
do
((${#array[@]} >= 2)) || continue
assoc["${array[@]:0:2}"]="${array[@]:2}"
done < data
for key in "${!assoc[@]}"
do
echo "${key} ---> ${assoc[${key}]}"
done