这是我的数组:
$ 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")'
您可以迭代数组的索引,即从
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
最简单的迭代方法似乎是:
#!/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
实际上,要准确回答最初的请求,代码应该是:
#!/usr/bin/bash
array=(one two three)
for i in ${!array[@]}; do
echo "$(($i+1)), ${array[$i]}"
done
...为了打印从 1 开始的元素编号,而不是零。
$(($i+1)) 是一个 Bash 复合 $(( )) 命令,用于计算算术表达式的“算术扩展”。