在shell脚本中读取矩阵中的值

时间:2016-04-13 05:59:32

标签: linux bash matrix

 # reading into array
 for(( i=0;i<2;i++)) do
     for((j=0;j<2;j++)) do
         read a[i][j]        
     done
 done

 # printing 
 for(( i=0;i<2;i++)) do
     for((j=0;j<2;j++) do
         echo -n ${a[i][j]}" "
     done
     echo  
 done

当我们读取矩阵

中的值时
2 3
4 5

它只分配值3 5 并打印

3 3
5 5

1 个答案:

答案 0 :(得分:2)

您可以通过几种方式使用索引算法模拟2D数组。这是一种常见的方法:

sudo

<强>输出

#!/bin/bash

## read values into a 1D array using nested loops and
## simulated 2D addressing
for ((i = 0; i < 2; i++)); do
    for ((j = 0; j < 2; j++)); do
        read a[$((i * 2 + j))]
    done
done

## Output the values contained in a simulated 2D manner
for ((i = 0; i < 2; i++)); do
    for ((j = 0; j < 2; j++)); do
        printf " %2d" ${a[$((i * 2 + j))]}
    done
    echo ""
done

通过一些额外的格式化,您可以制作漂亮的模拟2D阵列:

$ bash sim2darray.sh
1
2
3
4
  1  2
  3  4

示例使用/输出

#!/bin/bash

for ((i = 0; i < 5; i++)); do
    for ((j = 0; j < 5; j++)); do
        a[$((i * 5 + j))]=$((i * 5 + j))
    done
done

printf "\nThe simulated 5x5 2D array:\n\n"
for ((i = 0; i < 5; i++)); do
    [ "$i" -eq 0 ] && printf "[[" || printf " ["

    for ((j = 0; j < 5; j++)); do
        printf " %3d" ${a[$((i * 5 + j))]}
    done

    [ "$i" -eq 4 ] && printf " ]]\n\n" || printf " ]\n"
done