我想从bash数组中检索第N个单词。考虑以下数组定义:
words=("word1" "word2" "word3" "word4" "word5" "word6")
我想从变量值给定的间隔中选择从数组中提取的单词(空格是为了清楚起见,并不表示输出需要对齐):
n=1 # select items: word1 word2 word3 word4 word5 word6
n=2 # select items: word2 word4 word6
n=3 # select items: word3 word6
n=4 # select items: word4
这怎么办?
答案 0 :(得分:3)
与Danila Kiver described in a comment一样,只要您的数组是按数字索引且不稀疏的,以下内容将起作用:
for ((i=n-1; i<${#words[@]}; i+=n)); do
echo "${words[$i]}"
done