[英]Bash - expanding variable nested in variable
Noble StackOverflow readers, Noble StackOverflow阅读器,
I have a comma seperated file, each line of which I am putting into an array. 我有一个逗号分隔的文件,我将其每一行放入一个数组中。 Data looks as so... 数据看起来像这样...
25455410,GROU,AJAXa,GROU1435804437
25455410,AING,EXS3d,AING4746464646
25455413,TRAD,DLGl,TRAD7176202067
There are 103 lines and I am able to generate the 103 arrays without issue. 有103行,我能够毫无问题地生成103个数组。
n=1; while read -r OrdLine; do
IFS=',' read -a OrdLineArr${n} <<< "$OrdLine"
let n++
done < $WkOrdsFile
HOWEVER, I can only access the arrays as so... 但是,我只能这样访问数组...
echo "${OrdLineArr3[0]} <---Gives 25455413
I cannot access it with the number 1-103 as a variable - for example the following doesn't work... 我无法使用数字1-103作为变量来访问它-例如,以下操作不起作用...
i=3
echo "${OrdLineArr${i}[0]}
That results in... 导致...
./script2.sh: line 24: ${OrdLineArr${i}[0]}: bad substitution
I think that the answer might involve 'eval' but I cannot seem to find a fitting example to borrow. 我认为答案可能涉及“评估”,但我似乎找不到合适的例子来借鉴。 If somebody can fix this then the above code makes for a very easy to handle 2d array replacement in bash! 如果有人可以解决这个问题,那么上面的代码将使bash中的2d数组替换变得非常容易!
Thanks so much for you help in advance! 非常感谢您的提前帮助!
Dan 担
You can use indirect expansion . 您可以使用间接扩展 。 For example, if $key
is OrdLineArr4[7]
, then ${!key}
(with an exclamation point) means ${OrdLineArr4[7]}
. 例如,如果$key
是OrdLineArr4[7]
,则${!key}
(带有感叹号)表示${OrdLineArr4[7]}
。 (See §3.5.3 "Shell Parameter Expansion" in the Bash Reference Manual , though admittedly that passage doesn't really explain how indirect expansion interacts with arrays.) (请参见《 Bash参考手册 》中的第3.5.3节“ Shell参数扩展” ,尽管可以承认这段文字并不能真正解释间接扩展与数组的交互方式。)
I'd recommend wrapping this in a function: 我建议将其包装在一个函数中:
function OrdLineArr () {
local -i i="$1" # line number (1-103)
local -i j="$2" # field number (0-3)
local key="OrdLineArr$i[$j]"
echo "${!key}"
}
Then you can write: 然后您可以编写:
echo "$(OrdLineArr 3 0)" # prints 25455413
i=3
echo "$(OrdLineArr $i 0)" # prints 25455413
This obviously isn't a total replacement for two-dimensional arrays, but it will accomplish what you need. 显然,这并不是二维数组的完全替代,但是它将满足您的需要。 Without using eval
. 不使用eval
。
eval
通常不是一个好主意,但是您可以使用以下方法实现:
eval echo "\${OrdLineArr$i[0]}"
I would store each line in an array, but split it on demand: 我将每一行存储在一个数组中,但按需拆分:
readarray OrdLineArr < $WkOrdsFile
...
OrdLine=${OrdLineArr[i]}
IFS=, read -a Ord <<< "$OrdLine"
However, bash
isn't really equipped for data processing; 但是, bash
并没有真正用于数据处理。 it's designed to facilitate process and file management. 它旨在促进流程和文件管理。 You should consider using a different language. 您应该考虑使用其他语言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.