Pavel Stehule
Pavel Stehule

Reputation: 45795

reading associative arrays from file

I have a file with content:

( [datname]=template1 [datctype]=cs_CZ.utf-8 )
( [datname]=template0 [datctype]=cs_CZ.utf-8 )
( [datname]=postgres [datctype]=cs_CZ.utf-8 )
( [datname]=some\ stupid\ name [datctype]=cs_CZ.utf-8 )
( [datname]=jqerqwer,\ werwer [datctype]=cs_CZ.utf-8 )

I would to read every line and push context to associative array variable. I have no success with following code:

(cat <<EOF
( [datname]=template1 [datctype]=cs_CZ.utf-8)
( [datname]=template0 [datctype]=cs_CZ.utf-8 )
EOF                      
) |                      
while read r             
do                       
   declare -A row=("$r") 
   echo ${row[datname]}  
done;

I got a error:

test3.sh: line 8: row: ( [datname]=template1 [datctype]=cs_CZ.utf-8 ): must use subscript when assigning associative array

Is possible read array from file?

Upvotes: 6

Views: 4018

Answers (2)

nosid
nosid

Reputation: 50044

Make the following two changes: Remove the parentheses in the declare statement, and use read with the option -r (disable escape chars):

while read -r line; do
   declare -A row="$line" 
    ...  
done

Upvotes: 6

Dennis Williamson
Dennis Williamson

Reputation: 360095

Remove the parentheses from your declare statement since they're already in your data.

declare -A row="$r"

Upvotes: 2

Related Questions