Last active
March 6, 2016 23:28
-
-
Save setempler/7a148a432e3938f6692f to your computer and use it in GitHub Desktop.
Faking two-dimensional bash arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
OFS=$IFS # store field separator | |
IFS="${2: }" # define field separator | |
file=$1 # input file name | |
unset a # reference to line array | |
unset i j # index | |
unset m n # dimension | |
### input | |
i=0 | |
while read line | |
do | |
a=A$i | |
unset $a | |
declare -a $a='($line)' | |
i=$((i+1)) | |
done < $file | |
# store number of lines | |
m=$i | |
### output | |
for ((i=0; i < $m; i++)) | |
do | |
a=A$i | |
# get line size | |
# double escape '\\' for sub shell '``' and 'echo' | |
n=`eval echo \\${#$a[@]}` | |
for (( j = 0; j < $n; j++)) | |
do | |
# get field value | |
f=`eval echo \\${$a[$j]}` | |
# do something | |
echo "line $((i+1)) field $((j+1)) = '$f'" | |
done | |
done | |
IFS=$OFS |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
declare -A x | |
i=0 | |
j=3 | |
x[$i,$j]=new # use associative array with pseudo-dimensions | |
echo "${!x[@]}" | |
echo "${x[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit to
http://unix.stackexchange.com/questions/199348/dynamically-create-array-in-bash-with-variables-as-array-name
http://stackoverflow.com/a/31276568/1862762
See also
http://stackoverflow.com/questions/12317483/array-of-arrays-in-bash/35807116#35807116