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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:22:36  来源:igfitidea点击:

Bash reading from a file to an associative array

arraysbashassociative

提问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 Expansionhere ${array[@]:2}to get substring needed as the value of the assocarray. Also added -rto readto prevent backslash to act as an escape character.

Substring Expansion在此处使用${array[@]:2}以获取作为assoc数组值所需的子字符串。还添加-rread以防止反斜杠充当转义字符。

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