Bash reading from a file to an associative array

2019-06-15 18:51发布

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条回答
家丑人穷心不美
2楼-- · 2019-06-15 19:29
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
查看更多
登录 后发表回答