如何在bash中声明二维数组 [英] How to declare 2D array in bash

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

问题描述

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

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

在 C 中它看起来像这样:

In C it looks like this:

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

我如何为元素赋值?如在 C:

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

上面的例子创建了一个带有随机数的 4x5 矩阵并打印它转置,与示例结果

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

原理是:创建一个关联数组,其中索引为3,4这样的字符串.好处:

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

  • 可以用于任意维数组;) 像:30,40,2 用于 3 维.
  • 语法类似于数组${matrix[2,3]}
  • 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天全站免登陆