Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable as a key in an bash associative array

I'm trying to read the English dictionary in Linux into an associative array, using the words as keys and and predefined string as a value. This way I can look up words by key to see if they exist. Also I need all to words to be lowercase. It's fairly simple but the bash syntax is getting in my way. When I run the code below, I get a 'bad array subscript' error. Any thoughts as to why that might be ?

 function createArrayFromEnglishDictionary(){
        IFS=$'\n'
        while read -d $'\n' line; do
            #Read string into variable and put into lowercase.
            index=`echo ${line,,}`
            englishDictionaryArray[$index]="exists"
            done < /usr/share/dict/words
            IFS=$' \t\n'
    }
like image 635
Asgeir Avatar asked Mar 18 '12 20:03

Asgeir


4 Answers

$index is empty at some point. You also have a rather totally pointless use of echo assuming you wanted the line verbatim and not whitespace compressed. Just use index="${line,,}".

like image 122
jørgensen Avatar answered Oct 20 '22 00:10

jørgensen


I think following example will help..

$ declare -A colour
$ colour[elephant]="black"
$ echo ${colour[elephant]}
black

$ index=elephant
$ echo ${colour["$index"]}
black
like image 23
Jobin Avatar answered Oct 20 '22 01:10

Jobin


To use associative arrays in bash, you need bash version 4, and you need to declare the array as an associative array with declare -A englishDictionaryArray

http://www.linuxjournal.com/content/bash-associative-arrays

like image 24
glenn jackman Avatar answered Oct 20 '22 02:10

glenn jackman


Combining your work and other answers, try this:

I'm using GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)

#!/bin/bash
declare -A DICT
function createDict(){
    while read LINE; do
        INDEX=${LINE,,}
        DICT[$INDEX]="exists"
    done < /usr/share/dict/words
}

createDict

echo ${DICT[hello]}
echo ${DICT[acdfg]}
echo ${DICT["a's"]}
like image 30
philcolbourn Avatar answered Oct 20 '22 00:10

philcolbourn