使用一个变量名创建一个数组的bash,UNIX [英] Using a variable name to create an array bash, unix

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

问题描述

首先,我或许应该解释一下我想做的事情...

First I should perhaps explain what I want to do...


  • 我的文件'N'​​数量与行'N'量。我所知道的是
    该行数将是偶数。

  • 用户选择他们想要的文件。这个被保存到一个
    数组名为 $ {selected_sets [@]}

  • 该程序将打印屏幕上的一个随机选择奇数
    从随机选择的文件中的行。

  • 一旦该行已被打印,我不希望它再次打印...

大多数时候是好的,但我根据 $的内容有麻烦创建阵列{selected_sets [@]} ...我想我已经得到了我语法都错了:)

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

问题是 $ {I} [$ {#$ {I} [@]}] = $ X
我知道,我可以使用数组[$ {#数组[@]}] = $ X ,但我不知道如何使用一个变量名。

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)!!!

推荐答案

在一般情况下,这种类型的问题是解决了EVAL。如果你想要一个名为foo的变量,并具有可变栏=富,你只需做的:

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:


eval $bar=5

击(或SH)将其视为你输入

Bash (or any sh) treats that as if you had typed


foo=5

所以,你可能只需要编写:

So you may just need to write:


eval ${i}[\${#${i}[@]}]=$x

用合适的逃逸。 (一个有用的技术是回响,运行脚本并检查输出,并确保它看起来像要被评估的内容。替换'的eval')

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.)

这篇关于使用一个变量名创建一个数组的bash,UNIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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