如何申报在bash二维数组 [英] How to declare 2D array in bash

查看:261
本文介绍了如何申报在bash二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在bash声明一个二维数组,然后初始化为0。

在C中,它看起来是这样的:

  int类型的[4] [5] = {0};

我如何分配一个值的因素呢?在C:

  A [2] [3] = 3;


解决方案

您可以模拟它们例如使用哈希,但需要对前导零和许多其他的事情照顾。接下来的论证工作,但它是远离最优解。

 #!/斌/庆典
声明-A矩阵
NUM_ROWS = 4
NUM_COLUMNS = 5为((i = 1; I< = NUM​​_ROWS;我++))做
    为((J = 1; J< = NUM​​_COLUMNS; J ++))做
        矩阵[$ I,$ J] = $ RANDOM
    DONE
DONEF1 =%$(($ {#} NUM_ROWS +1))的
F2 =%9printf的$ F1''
为((i = 1; I< = NUM​​_ROWS;我++))做
    printf的$ F2$ I
DONE
回声为((J = 1; J< = NUM​​_COLUMNS; J ++))做
    printf的$ F1附加$ J
    为((i = 1; I< = NUM​​_ROWS;我++))做
        printf的$ F2$ {矩阵[$ I,$ J]}
    DONE
    回声
DONE

上面的例子中创建了随机数的一个4x5矩阵,并打印换位,用这个例子的结果。

  1 2 3 4
 1 18006 31193 16110 23297
 2 26229 19869 19837 1140
 3 8192 2181 25512 2318
 4 3269 25516 18701 7977
 5 31775 17358 4468 30345

其原理是:制作一个关联数组,其中索引像 3,4 的字符串。好处:


  • 这是可能的,可以用于任何维数组;),如: 30,40,2 3维

  • 语法是接近C状阵列 $ {矩阵[2,3]}

I'm wondering how to declare a 2D array in bash and then initialize to 0.

In C it looks like this:

int a[4][5] = {0};

And how do I assign a value to an element? As in C:

a[2][3] = 3;

解决方案

You can simulate them for example with hashes, but need care about the leading zeroes and many other things. The next demonstration works, but it is far from optimal solution.

#!/bin/bash
declare -A matrix
num_rows=4
num_columns=5

for ((i=1;i<=num_rows;i++)) do
    for ((j=1;j<=num_columns;j++)) do
        matrix[$i,$j]=$RANDOM
    done
done

f1="%$((${#num_rows}+1))s"
f2=" %9s"

printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
    printf "$f2" $i
done
echo

for ((j=1;j<=num_columns;j++)) do
    printf "$f1" $j
    for ((i=1;i<=num_rows;i++)) do
        printf "$f2" ${matrix[$i,$j]}
    done
    echo
done

the above example creates a 4x5 matrix with random numbers and print it transposed, with the example result

           1         2         3         4
 1     18006     31193     16110     23297
 2     26229     19869      1140     19837
 3      8192      2181     25512      2318
 4      3269     25516     18701      7977
 5     31775     17358      4468     30345

The principle is: Creating one associative array where the index is an string like 3,4. The benefits:

  • it's possible to use for any-dimension arrays ;) like: 30,40,2 for 3 dimensional.
  • the syntax is close to "C" like arrays ${matrix[2,3]}

这篇关于如何申报在bash二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆