在Bash Script中,如何读取文件并将所有行拆分为二维数组

时间:2016-04-08 18:21:20

标签: linux bash shell

档案内容:

Class_one 23
Class_two 17
Class-three 22
..

如何读取文件并将所有行拆分为二维数组?喜欢java。喜欢:

arr[0][0] = Class_one    arr[0][1] = 23
arr[1][0] = Class_two    arr[1][1] = 17

感谢。

2 个答案:

答案 0 :(得分:0)

GNU bash没有二维数组。解决方法是关联数组。

#!/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

请参阅:help declareman bash

答案 1 :(得分:0)

@ Cyrus的方法涉及关联数组,这显然仅在bash 4.0及更高版本中。以下是适用于bash sub-4.0的内容。请注意,现在Mac仍然以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