Reading associative arrays from a 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 read each line and click context on an associative array variable. I have no success in the 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 an error:

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

Is it possible to read an array from a file?

+6
source share
2 answers

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

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

Remove the parentheses from the declare statement as they are already in your data.

 declare -A row="$r" 
+2
source

Source: https://habr.com/ru/post/916746/


All Articles