bash + for循环+输出索引号和元素

问题描述 投票:0回答:3

这是我的数组:

$ ARRAY=(one two three)

如何打印数组,以便获得如下输出:

index i, element[i]
使用下面使用的
printf
for
循环

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
3个回答
39
投票

您可以迭代数组的索引,即从

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

20
投票

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

#!/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

0
投票

实际上,要准确回答最初的请求,代码应该是:

#!/usr/bin/bash

array=(one two three)
for i in ${!array[@]}; do
  echo "$(($i+1)), ${array[$i]}"
done

...为了打印从 1 开始的元素编号,而不是零。

$(($i+1)) 是一个 Bash 复合 $(( )) 命令,用于计算算术表达式的“算术扩展”。

© www.soinside.com 2019 - 2024. All rights reserved.