2

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!

3
  • Associative arrays or maps store key-value pairs. What you want is a multimap, which allows multiple values to be associated with a single key. Personally, I would have switched to Python by now since the bash script is becoming too complex. Commented Oct 11, 2013 at 0:05
  • Thank you Dennis, misunderstanding about associative arrays on my part Commented Oct 11, 2013 at 1:23
  • Keep in mind that bash is not intended for data processing, but for running other processes. Commented Oct 11, 2013 at 12:41

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh okay, thank you. Misunderstanding about associative arrays on my part :)
@warlord786 - no worries :) - You learned something from SO today - thats what makes it all worth it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.