Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading associative arrays from file

Tags:

bash

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?

like image 251
Pavel Stehule Avatar asked May 26 '12 13:05

Pavel Stehule


1 Answers

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
like image 99
nosid Avatar answered Sep 29 '22 17:09

nosid