warlord786
warlord786

Reputation: 23

Associative Arrays in Bash

I am attempting to take a file and store the items from the file into an associative array in bash. An associative array might not be the best course for my action, but from my research it appears to be a good fit. I have a file that looks like the following:

personid
phone
phone
phone
personid
phone
phone
phone

Please note, persionid is always 20 digits, and phone is always 10. There is nothing else in this file, and no whitespace, just one of these per line. I wanted to map these to an associative array with my key being personid and my value being phone.

The code I've worked on regarding this piece is the following:

declare -A person

while read key; do

    if [ ${#key} -eq 20 ] ; then
        personID="$key"
    else
       phone="$key"
    fi

    person=( ["$personID"]="$phone" )

done < myFile.txt

for i in "${!person[@]}"
do
    echo "key: $i"
    echo "value: ${person[$i]}"
done

It will correctly store and print one personID as the key and one phone as the value....but there should be multiple values for phone. I'm thinking when I assign person, I must be doing that wrong, or have it in the wrong placed. But I've played around with it for quite sometime now and can't get it right. Never used associative arrays before, so having a little trouble. Thanks in advance for the help!

Upvotes: 2

Views: 2481

Answers (1)

Digital Trauma
Digital Trauma

Reputation: 15986

Associative arrays are no different to any other arrays in that there will always be exactly a 1:1 mapping from key (or index) to value. In your case, you want a 1:many mapping from key (personID) to values (phone numbers). One way to do this would simply to store a list of phone numbers which is effectively the "single" value mapped to a personID. You can construct your list however you like, with whitespace, or comma delimiters or anything else.

For example if you want : as your delimiter, you could do this to add each phone number to the list:

if [ -n ${person[$personID]} ] ; then
    person[$personID]}="${person[$personID]}:$phone"
else
    person[$personID]}="$phone"
fi

Upvotes: 1

Related Questions