【问题标题】:Fill an array with a loop in BASH在 BASH 中使用循环填充数组
【发布时间】:2013-06-25 22:54:22
【问题描述】:

我想像这样在 bash 中自动填充一个数组:

200 205 210 215 220 225 ... 4800

我尝试过这样的:

for i in $(seq 200 5 4800);do
    array[$i-200]=$i;
done

你能帮帮我吗?

【问题讨论】:

    标签: arrays bash for-loop


    【解决方案1】:

    你可以使用+=操作符:

    for i in $(seq 200 5 4800); do
        array+=($i)
    done
    

    【讨论】:

      【解决方案2】:

      你可以简单地:

      array=( $( seq 200 5 4800 ) )
      

      你已经准备好你的数组了。

      【讨论】:

        【解决方案3】:

        按照 的方式进行操作:

        array=( {200..4800..5} )
        

        【讨论】:

          【解决方案4】:

          您可能会在使用这些方法时遇到内存(或行的最大长度)问题,所以这里有另一个问题:

          # function that returns the value of the "array"
          value () { # returns values of the virtual array for each index passed in parameter
             #you could add checks for non-integer, negative, etc
             while [ "$#" -gt 0 ]
             do
                #you could add checks for non-integer, negative, etc
                printf "$(( ($1 - 1) * 5 + 200 ))"
                shift
                [ "$#" -gt 0 ] && printf " "
             done 
          }
          

          这样使用:

          the_prompt$ echo "5th value is : $( value 5 )"
          5th value is :  220
          
          the_prompt$ echo "6th and 9th values are : $( value 6 9 )"
          6th and 9th values are :  225 240
          

          【讨论】:

            猜你喜欢
            • 2012-04-16
            • 2015-01-07
            • 1970-01-01
            • 1970-01-01
            • 2020-09-11
            • 2014-04-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多