簡體   English   中英

在Bash Script中,如何讀取文件並將所有行拆分為二維數組

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

文件內容:

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

謝謝。

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

@ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM