11

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
Josep Alsina
  • 2,762
  • 1
  • 16
  • 12
user3598639
  • 111
  • 1
  • 3

1 Answers1

17
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
a5hk
  • 7,532
  • 3
  • 26
  • 40
  • 6
    You could add a few improvements: 1. Put `IFS=,` for the `read` command and not have to fiddle saving `IFS` and restoring it. 2. In the loop add `((${#array[@]}>=2)) || continue` or something similar to get rid of empty lines. 3. Write your assignment as `assoc["${array[@]::2}"]=${array[@]:2}`. – gniourf_gniourf May 03 '14 at 10:42
  • @gniourf_gniourf, Is `${array[@]::2}` form of `${parameter:offset:length}` with ommited `offset` and then the `offset` is assumed zero? – a5hk May 03 '14 at 11:21