【问题标题】:bash + for loop + output index number and elementbash + for 循环 + 输出索引号和元素
【发布时间】:2016-07-27 02:10:49
【问题描述】:

这是我的数组:

$ ARRAY=(one two three)

我如何打印数组,以便得到如下输出:index i, element[i] 使用下面使用的 printffor 循环

1,one
2,two
3,three

一些笔记供我参考

1种方式打印数组:

$ printf "%s\n" "${ARRAY[*]}"
one two three

2种方式打印数组

$ printf "%s\n" "${ARRAY[@]}"
one
two
three

3种方式打印数组

$ for elem in "${ARRAY[@]}"; do  echo "$elem"; done
one
two
three

4种方式打印数组

$ for elem in "${ARRAY[*]}"; do  echo "$elem"; done
one two three

查看数组的另一种方式

$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'

【问题讨论】:

    标签: arrays bash printf


    【解决方案1】:

    您可以遍历数组的索引,即从0${#array[@]} - 1

    #!/usr/bin/bash
    
    array=(one two three)
    
    # ${#array[@]} is the number of elements in the array
    for ((i = 0; i < ${#array[@]}; ++i)); do
        # bash arrays are 0-indexed
        position=$(( $i + 1 ))
        echo "$position,${array[$i]}"
    done
    

    输出

    1,one
    2,two
    3,three
    

    【讨论】:

      【解决方案2】:

      最简单的迭代方式似乎是:

      #!/usr/bin/bash
      
      array=(one two three)
      
      # ${!array[@]} is the list of all the indexes set in the array
      for i in ${!array[@]}; do
        echo "$i, ${array[$i]}"
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2020-11-20
        • 2013-10-12
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多