Bash reading from a file to an associative array

五迷三道 提交于 2019-12-08 15:34:46

问题


I'm trying to write a script in bash using an associative array. I have a file called 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

回答1:


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.

Improved based on @gniourf_gniourf's suggestions:

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


来源:https://stackoverflow.com/questions/23442173/bash-reading-from-a-file-to-an-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!