arrays - 在 bash 中循环切片数组的索引

标签 arrays bash for-loop slice

我想从第二个索引开始遍历数组的索引。我该怎么做?

我试过:

myarray=( "test1" "test2" "test3" "test4")
for i in ${!myarray[@]:1}
do
    # I only print the indices to simplify the example
    echo $i 
done

但不起作用。

显然这是可行的:

myarray=( "test1" "test2" "test3" "test4")
myindices=("${!myarray[@]}")
for i in ${myindices[@]:1}
do
    echo $i
done

但如果可能,我想将所有内容组合在 for 循环语句中。

最佳答案

使用#参数长度扩展:

myarray=( "test1" "test2" "test3" "test4")
for (( i=1;  i < ${#myarray[@]};  i++ ))
do
    # only print the indices to simplify the example
    echo $i 
done

请注意,! 间接扩展 运算符显然与子字符串扩展 不兼容,因为:

echo "${!myarray[@]:2}"

生成错误代码 1 并输出到 STDERR:

bash: test1 test2 test3 test4: bad substitution

至少对于 bash 的当前版本,v.4.4 和更早版本。不幸的是,man bash 没有充分说明子字符串扩展 不适用于间接扩展

关于arrays - 在 bash 中循环切片数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637445/

相关文章:

c# - 使用 Newtonsoft 解析 JSON 数组

bash - 如何遍历 find 返回的文件名?

bash - 如何在搜索模式中使用带有 sed 的 xargs

java - for循环中同时初始化两个变量

ios - 在 Swift 中对字符串数组进行排序

arrays - 从另一个类读取数组

php - 获取可能的数组组合

php - 从 php 启动一个独立进程(通过 httpd)

javascript - 事件中的变量

bash - 使用 tr 删除多个文件中的换行符?