Bash shell函数,用于将文件读取到数组

Bash shell函数,用于将文件读取到数组,bash,shell,Bash,Shell,我正在编写一个shell脚本函数,用于读取给定文件并将数据存储到二维数组中 File.txt a1 b1 c1 a2 b2 c2 a3 b3 c3 # Let's just assume 3 rows 其思想是使用函数签名“read_data File.txt array num_rows” read_data() { if [ ! -f $1 ]; then echo "Failed to read hosts ($1 not found)"; exit; fi

我正在编写一个shell脚本函数,用于读取给定文件并将数据存储到二维数组中

File.txt

a1 b1 c1
a2 b2 c2
a3 b3 c3
# Let's just assume 3 rows
其思想是使用函数签名“read_data File.txt array num_rows”

read_data() {

  if [ ! -f $1 ]; then
    echo "Failed to read hosts ($1 not found)"; 
    exit;
  fi  

  while read -r line; do

    # skip the comments
    { [[ "$line" =~ ^#.*$ ]] || [[ -z $line ]] ;} && continue

    # Parse the line
    read -a tokens <<< $line

    if [ ${#tokens[@]} == 3 ]; then

      # Extract the user/host/home
      eval $2[\$$3, 0]=\${tokens[0]}
      eval $2[\$$3, 1]=\${tokens[1]}
      eval $2[\$$3, 2]=\${tokens[2]}
      eval $3=$(($3+1))

    else
      echo "Wrong line format '$line'"
    fi  

  done < $1
}
我得到的是
num_rows
等于
3
,但数组中存储的内容是

pnt_data() {
  for ((i=0; i<$2; i++)); do

      eval a=\${$1[$i, 0]} 
      eval b=\${$1[$i, 1]} 
      eval c=\${$1[$i, 2]} 

      echo $a $b $c
  done
}

pnt_data array num_rows

a3 b3 c3
a3 b3 c3
a3 b3 c3
pnt_数据(){

for((i=0;i数组索引在算术上下文中求值,逗号运算符的工作方式是求值左侧操作数,忽略它,然后求值到右侧操作数。例如:

$ echo $((3,0))
0
$ echo $((3+9,0))
0
$ echo $((a,0))
0
因此,以下所有赋值都相当于
foo[0]=bar

foo[3,0]=bar     # ignore 3
foo[3+9,0]=bar   # 3+9=12, ignore 12
foo[a,0]=bar     # ignore whatever the value of a is
如果要模拟多维索引,则需要使用关联数组,以便用作索引的字符串在使用之前不会进行算术展开

declare -A array  # capital A, not lowercase a
num_rows=0
read_data File.txt array num_rows

数组索引在算术上下文中求值,逗号运算符的工作方式是求值左侧操作数,忽略它,然后求值到右侧操作数。例如:

$ echo $((3,0))
0
$ echo $((3+9,0))
0
$ echo $((a,0))
0
因此,以下所有赋值都相当于
foo[0]=bar

foo[3,0]=bar     # ignore 3
foo[3+9,0]=bar   # 3+9=12, ignore 12
foo[a,0]=bar     # ignore whatever the value of a is
如果要模拟多维索引,则需要使用关联数组,以便用作索引的字符串在使用之前不会进行算术展开

declare -A array  # capital A, not lowercase a
num_rows=0
read_data File.txt array num_rows

Buh不支持2D数组,选择不同的语言。<代码> AWK < /COD>支持它们。我个人会考虑Perl或Python。BASH不支持2D数组,选择不同的语言。<代码> AWK < /Cord>支持它们。个人而言,我会考虑Perl或Python。