数组的值赋给变量bash脚本 [英] Assigning the value of an array to a variable bash script

查看:131
本文介绍了数组的值赋给变量bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想请教一下我使用二维数组元素的值赋给变量的语法。这基本上是什么,我要做的:我有字符的2维数组和字符串名为SUB_STRING,获取数组中某元素的值,并把它称为whole_string另一个字符串

 为((J = 1; J< = NUM​​_COLUMNS; J ++))做
      为((i = 1; I< = NUM​​_ROWS;我++))做


  

在阵列矩阵中的元素[I,J]的值分配给子
  字符串


  whole_string =$ whole_String $ SUB_STRING
    DONE
DONE

我想知道如何将数组的值分配给子字符串我有。谢谢


解决方案

通过电流的bash您可以将一个关联数组来创建多维数组。

 #!/斌/庆典声明-A A#声明关联数组
NUM_ROWS = 7
NUM_COLUMNS = 9#填充阵列
为((J = 1; J< = NUM​​_ROWS; J ++))做
  为((i = 1; I< = NUM​​_COLUMNS;我++))做
    A [附加$ J,$ i] =$ Y:$ I#填补行:列
  DONE
DONE#打印数组
为((J = 1; J< = NUM​​_ROWS; J ++))做
  为((i = 1; I< = NUM​​_COLUMNS;我++))做
    回声-n$ {A [附加$ J,$ I]}
  DONE
  回声
DONE

输出(9×7阵列):


1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9
2:1 2:2 2:3 2:4 2:5 2:6 2:7 2:8 2:9
3:1 3:2 3:3 3:4 3:5 3:6 3:7 3:8 3:9
4:1 4:2 4:3 4:4 4:5 4:6 4:7 4:8 4:9
5:1 5:2 5:3 5:4 5:5:6 5 7 5 8 5:9
6:1 6:2 6:3 6:4 6:5 6:6 6:7 6:8 6:9
7:1 7:2 7:3 7:4 7:5 7:6 7:7:8 7:9

I want to ask about the syntax i use to assign a value of a two dimensional array element to a variable. this is basically what i am trying to do: I have a 2 dimensional array of characters and a string called sub_string that gets the value of a particular element in the array and put it in another string called whole_string

for ((j=1;j<=num_columns;j++)) do
      for ((i=1;i<=num_rows;i++)) do

Assigning the value of the element [i,j] in the array matrix to a sub string

    whole_string="$whole_String$sub_string"
    done
done

I want to know how to assign the value of the array to the sub string i have. thank you

解决方案

With a current bash you can divert an associative array to create multidimensional arrays.

#!/bin/bash

declare -A A    # declare associative array A
num_rows=7
num_columns=9

# fill array
for ((j=1;j<=num_rows;j++)) do
  for ((i=1;i<=num_columns;i++)) do
    A[$j,$i]="$j:$i"   # fill with row:column
  done
done

# print array
for ((j=1;j<=num_rows;j++)) do
  for ((i=1;i<=num_columns;i++)) do
    echo -n "${A[$j,$i]} "
  done
  echo
done

Output (9x7 array):

1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 
2:1 2:2 2:3 2:4 2:5 2:6 2:7 2:8 2:9 
3:1 3:2 3:3 3:4 3:5 3:6 3:7 3:8 3:9 
4:1 4:2 4:3 4:4 4:5 4:6 4:7 4:8 4:9 
5:1 5:2 5:3 5:4 5:5 5:6 5:7 5:8 5:9 
6:1 6:2 6:3 6:4 6:5 6:6 6:7 6:8 6:9 
7:1 7:2 7:3 7:4 7:5 7:6 7:7 7:8 7:9 

这篇关于数组的值赋给变量bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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