【问题标题】:Variable inside array call results in bad substitution [duplicate]数组调用内部的变量导致替换错误[重复]
【发布时间】:2021-02-08 01:15:36
【问题描述】:

我正在尝试在循环中访问数组中的数据。

这个命令运行良好..

echo "text: ${hnr1[1]}"

还有这个:

echo "text: ${hnr1[$loopnr]}"

但是,这让我很头疼;

echo "text: ${hnr$loopnr[1]}"

将导致:

**: text: ${hnr$loopnr[1]}: bad substitution**

有人知道怎么解决吗?

编辑: 不要挂在循环上,这是我测试东西的一种方式.. 数据为:

array **hnr1** has **20** entries regarding **map 1**
array **hnr2** has **20** entries regarding **map 2**

所以我的最佳功能是:

' data=${hnr$mapnr[$field]} '

【问题讨论】:

  • 你想用echo "text: ${hnr$loopnr[1]}"做什么? “访问数据”如何?数据是什么格式的?
  • 数据在名为 hnr1 的数组中 --> hnr66 数据是字符串/整数
  • 这是一个数组,还是这 66 个单独的变量?数组(通常)在 bash 中声明为 hnr=(value1 value2 …)
  • hnr1 包含 20 个关于 map1 的值,hnr2 包含 20 个 map2 的值等等......

标签: arrays bash variables


【解决方案1】:

最好的办法是使用关联数组而不是 66 个不同的数组变量。您可以从awk 借用一个页面并使用不会出现在键中的分隔符来模拟多维数组:

#!/usr/bin/env bash

declare -A hnr
hnr[1,0]=foo
hnr[1,1]=bar
#...
hnr[66,0]=cat
hnr[66,1]=dog
# Or all at once declare -A nhr=([1,0]=foo ... [66,1]=dog)

loopnr=66
echo "Text: ${hnr[$loopnr,1]}"

你也可以使用bashindirect expansion,但是上面的方式会简单很多,也更容易理解:

declare -a hnr66=(ball bat)
loopnr=66
# Build up the variable name - note the array index has to be part of this
varname="hnr$loopnr[1]"
# And use it.
echo "Text: ${!varname}"

【讨论】:

  • 现在我已经有了如下数据:hnr1 包含 20 个关于 map1 的值,hnr2 包含 20 个 map2 的值等等.. 必须有某种逻辑方式可以通过 ${hnr$loopnr[1 ]}(或其他有效的方法?)
  • @JoBe 您当然会重写其余代码以匹配使用关联数组来存储所有内容。
  • 我对数组很陌生,但这看起来很简单,会... echo "Text: ${hnr[$loopnr,$val]}" 也可以吗?
  • @JoBe:请参阅 Shawn 回答的下半部分,他向您展示了如何使用 indirect expansion 访问当前数组中的值......最终结果是它是可行的,但有点令人费解;至于您的第二条评论/问题回复:echo "Text ..." ...“如有疑问,请尝试一下!”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多