使用变量名创建数组 bash, unix
首先,我也许应该解释一下我想要做什么...
- 我有 'n' 个文件,其中有 'n' 行。我所知道的是 行数将是偶数。
- 用户选择他们想要的文件。这被保存到 名为
${selected_sets[@]}
的数组。 - 该程序将打印到屏幕上随机选择的“奇数” 来自随机选择的文件的行。
- 打印该行后,我不想再次打印它...
大部分都很好,但我在根据 ${selected_sets[@]}
的内容创建数组时遇到问题...我想我的语法全错了:)
for i in ${selected_sets[@]}
do
x=1
linecount=$(cat $desired_path/$i | wc -l) #get line count of every set
while [ $x -le $linecount ]
do ${i}[${#${i}[@]}]=$x
x=$(($x+2)) # only insert odd numbers up to max limit of linecount
done
done
问题是 ${i}[${#${i}[@]}]=$x
我知道我可以使用 array[${#array[@]}]=$x 但我不知道如何使用变量名。
任何想法都将受到欢迎(我真的很难过)!
First I should perhaps explain what I want to do...
- I have 'n' amounts of files with 'n' amount of lines. All I know is
that the line count will be even. - The user selects the files that they want. This is saved into an
array called${selected_sets[@]}
. - The program will print to screen a randomly selected 'odd numbered'
line from a randomly selected file. - Once the line has been printed, I don't want it printed again...
Most of it is fine, but I am having trouble creating arrays based on the contents of ${selected_sets[@]}
... I think I have got my syntax all wrong :)
for i in ${selected_sets[@]}
do
x=1
linecount=$(cat $desired_path/$i | wc -l) #get line count of every set
while [ $x -le $linecount ]
do ${i}[${#${i}[@]}]=$x
x=$(($x+2)) # only insert odd numbers up to max limit of linecount
done
done
The problem is ${i}[${#${i}[@]}]=$x
I know that I can use array[${#array[@]}]=$x
but I don't know how to use a variable name.
Any ideas would be most welcome (I am really stumped)!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,这类问题都是用eval来解决的。如果你想要一个名为“foo”的变量并且有一个变量 bar=“foo”,你只需这样做:
Bash(或任何 sh)将其视为就像你键入了
So 你可能只需要编写:
并带有合适的转义符。 (一种有用的技术是将“eval”替换为“echo”,运行脚本并检查输出并确保它看起来像您想要评估的内容。)
In general, this type is question is solved with eval. If you want a a variable named "foo" and have a variable bar="foo", you simply do:
Bash (or any sh) treats that as if you had typed
So you may just need to write:
with suitable escapes. (A useful technique is to replace 'eval' with 'echo', run the script and examine the output and make sure it looks like what you want to be evaluated.)
您可以使用
declare
命令创建命名变量,我只是不确定如何引用这些变量,我现在没有时间调查这一点。
使用数组:
小心!我没有测试以上任何一项。华泰
You can create named variables using the
declare
commandI'm just not sure how you would then reference those variables, I don't have time to investigate that now.
Using an array:
Beware! I didn't test any of the above. HTH