0

I've got a file test.tmp, and the file has the following content.

AAA 100
BBB 200
CCC 300

I'd like to create an associated array to save this information, so the key value pair would be

[AAA]=100, [BBB],200...

the code in the following is what I tried though it didn't work:

declare -A index
while read line
do
     index[`echo $line | awk '{print $1}']=`echo $line | awk '{print $2}'`)
done < test.tmp

This is the code I used to check the array

for i in ${!index[@]}
do
        echo "index $i: ${index[i]}"
done
halfer
  • 19,824
  • 17
  • 99
  • 186
Tilei Liu
  • 155
  • 1
  • 6
  • 3
    Use `read -r key value` instead of `read line`!! Then `index[$key]="$value"`... – F. Hauri - Give Up GitHub Sep 25 '22 at 06:39
  • See how tu use `read`: [How to set environment variables from .env file](https://stackoverflow.com/a/43267603/1765658) – F. Hauri - Give Up GitHub Sep 25 '22 at 06:44
  • HI, i've changed my code with what you suggested and used the following code to check, but the value isn't written in the array ``` for i in ${!index[@]} do echo "index $i: ${index[i]}" done ``` – Tilei Liu Sep 25 '22 at 06:45
  • 2
    @TileiLiu you left out a `$` ... `${index[i]}` should be `${index[$i]}`; an alternative way to check the contents of the array: `typeset -p index` (or `declare -p index`) – markp-fuso Sep 25 '22 at 14:38

0 Answers0