Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 从bash数组中选择每n个条目_Arrays_Bash - Fatal编程技术网

Arrays 从bash数组中选择每n个条目

Arrays 从bash数组中选择每n个条目,arrays,bash,Arrays,Bash,我想从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 # s

我想从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
如何做到这一点?

因为,只要您的数组是数字索引的,而不是稀疏的,以下内容就可以工作:

for ((i=n-1; i<${#words[@]}; i+=n)); do
  echo "${words[$i]}"
done
如前所述,只要您的数组是数字索引且不是稀疏的,以下操作就可以工作:

for ((i=n-1; i<${#words[@]}; i+=n)); do
  echo "${words[$i]}"
done

对于i=0;你打算成为一个评论角色吗?如果是这样的话,会更清楚。顺便说一句,多个特定的单词并没有说明这些单词是如何被指定的——我们不得不推断,正如最初所问的那样。我试着编辑,使问题不那么模棱两可;今后提出问题时,请尽量具体明确,不要依赖读者从例子中推断;你打算成为一个评论角色吗?如果是这样的话,会更清楚。顺便说一句,多个特定的单词并没有说明这些单词是如何被指定的——我们不得不推断,正如最初所问的那样。我试着编辑,使问题不那么模棱两可;今后提出问题时,请尽量具体明确,不要依赖读者从例子中推断。