Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash reading from a file to an associative array

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
like image 681
user3598639 Avatar asked May 03 '14 08:05

user3598639


1 Answers

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
like image 75
a5hk Avatar answered Oct 11 '22 12:10

a5hk