Content of the file:
Class_one 23 Class_two 17 Class-three 22 ..
How to read the file and split all lines into a two-dimensional array? like java. Like:
arr[0][0] = Class_one arr[0][1] = 23 arr[1][0] = Class_two arr[1][1] = 17
thanks.
Advertisement
Answer
GNU bash has no two-dimensional array. A workaround is an associative array.
#!/bin/bash
declare -A arr # declare an associative array
declare -i c=0
# read from stdin (from file)
while read -r label number; do
arr[$c,0]="$label"; arr[$c,1]="$number"
c=c+1
done < file
# print array arr
for ((i=0;i<${#arr[@]}/2;i++)); do
echo "${arr[$i,0]} ${arr[$i,1]}"
done
See: help declare and man bash