简体   繁体   English

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

[英]Read value in matrix in shell script

 # 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

When we read the values in matrix 当我们读取矩阵中的值时

2 3
4 5

it assigns only the values 3 5 and prints 它只分配值3 5并打印

3 3
5 5

You can simulate 2D arrays with index arithmetic in a couple of ways. 您可以通过两种方法使用索引算法来模拟2D数组。 Here is a common method: 这是一种常用方法:

#!/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

Output 产量

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

With a few additional bits of formatting you can make a nice looking simulated 2D array: 通过其他一些格式化,您可以创建一个漂亮的模拟2D数组:

#!/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

Example Use/Output 使用/输出示例

$ bash sim2darray.sh

The simulated 5x5 2D array:

[[   0   1   2   3   4 ]
 [   5   6   7   8   9 ]
 [  10  11  12  13  14 ]
 [  15  16  17  18  19 ]
 [  20  21  22  23  24 ]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM