Skip to content

Instantly share code, notes, and snippets.

@setempler
Last active March 6, 2016 23:28
Show Gist options
  • Save setempler/7a148a432e3938f6692f to your computer and use it in GitHub Desktop.
Save setempler/7a148a432e3938f6692f to your computer and use it in GitHub Desktop.
Faking two-dimensional bash arrays
#!/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
#!/bin/bash
declare -A x
i=0
j=3
x[$i,$j]=new # use associative array with pseudo-dimensions
echo "${!x[@]}"
echo "${x[@]}"