in Bash Script, how to read a file and split all lines into a two-dimensional array

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.

Answers


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


@Cyrus's approach involves associative arrays which is noticeably only in bash 4.0 and up. Below is what works for bash sub-4.0. Note that nowadays Mac's are still shipped w/ bash 3.x.

#!/bin/bash
l=0; while read -a a$l; do
    let l++;
done < ${data_file_name}

## now everything is stored in the 2D array ${a};
## $(($l+1)) is #rows, and ${#a0[@]} is #cols;
## elements can be accessed in the form of "ai[j]";
## e.g., a0[0] is the element at (0,0);
## but to access "ai[j]" using var ${i} and ${j}
## as indexes can be a just little tricky

echo "#rows: $((l+1))"
echo "#cols: ${#a0[@]}"$'\n'
echo "element at (0, 0): ${a0[0]}"

## the following shows how to access an element at (i,j)
i=1; j=1
tmp_a="a${i}[${j}]"; echo "element at ($i, $j): ${!tmp_a}"$'\n'

## the following shows how to iterate through the 2D array
echo "all elements printed from top left to bottom right:"
for i in `eval echo {0..$l}`; do
    for j in `eval echo {0.."$((${#a0[@]}-1))"}`; do
        tmp_a="a${i}[${j}]"; echo ${!tmp_a}
    done
done

Need Your Help

Set CMSampleBuffer samples attachment (Swift)

ios swift h.264

I'm trying to set the kCMSampleAttachmentKey_DisplayImmediately for each of my samples in the CMSampleBuffer.

How to capitalize each word of a NSString

objective-c cocoa cocoa-touch

I am trying to figure out how to take a given NSString and convert it to camel case. I have seen lots of code samples out there for going back and forth between underscores_ and camel-case, but I am