bash + for循环+输出索引号和元素 [英] bash + for loop + output index number and element
本文介绍了bash + for循环+输出索引号和元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数组:
$ ARRAY=(one two three)
如何打印数组,以得到如下输出:index i, element[i]
使用下面使用的printf
或for
循环
How do I print the array so I have the output like: index i, element[i]
using the printf
or for
loop I use below
1,one
2,two
3,three
一些注意事项供我参考
一种打印数组的方法:
$ 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
.
You can iterate over the indices of the array, i.e. from 0
to ${#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
这篇关于bash + for循环+输出索引号和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文