1 year ago

#356715

test-img

Leoš Nevoral

How to force bash to assign string as key in array

I found some strange behaviour of Bash while working with associative array. It all assigns to the position 0 in array. Any way to force it to keep the string as key? Here is the code and output..

countCountry() {
    limitInput
    out=$(awk -F, '{print $8}' <<<$valid)
    occuringCountries=$(awk /./ <<<$out | grep -v "CZ" | sort -n | uniq)
    for i in $occuringCountries; do
        countries[$i]=$((${countries[$i]} + $(grep -c "$i" <<<$out)))
        echo $i
    done
}

for i in "${!countries[@]}"; do
    printf "%s: %s\n" "$i" "${countries["$i"]}"
done

The filtered input has a shortcut of country on each line with some empty lines or "CZ" representing my country of origin, which is skipped.

The occuring countries are: AE \n AR \n AT \n BE \n CA \n CH \n CM \n CR \n DE \n DK \n DO \n EG \n ES \n FR \n GB \n GR \n HU \n ID \n IE \n IL \n IT \n MT \n MU \n NL \n OM \n PH \n PL \n PT \n SA \n SE \n SI \n SK \n TH \n TR \n US

but the final output at end is this:

0: 412 (this is the value of all countries combined)

I tried different kinds of quotes surrounding the array index with no success.

bash

associative-array

0 Answers

Your Answer

Accepted video resources