Bash for 循环获取上一项和下一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13659047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:54:28  来源:igfitidea点击:

Bash for loop get previous and next item

bashloops

提问by Guillaume

I would like to do a loop and inside the loop get the previous and the next item.

我想做一个循环并在循环内获取上一个和下一个项目。

Currently, I am using the following loop:

目前,我正在使用以下循环:

for file in $dir;do
    [...do some things...]
done

Can I do things like in C, for example, file[i-1]/file[i+1] to get the previous and the next item? Is there any simple method to do this?

我可以在 C 中做一些事情,例如,file[i-1]/file[i+1] 来获取上一个和下一个项目吗?有没有什么简单的方法可以做到这一点?

回答by Vivek

declare -a files=(*)
for (( i = 0; i < ${#files[*]}; ++ i ))
do
  echo ${files[$i-1]} ${files[$i]} ${files[$i+1]}
done

In the first iteration, the index -1 will print the last element and in the last iteration, the index max+1 will not print anything.

在第一次迭代中,索引 -1 将打印最后一个元素,在最后一次迭代中,索引 max+1 将不打印任何内容。

回答by Pavel Strakhov

Try this:

尝试这个:

previous=
current=
for file in *; do
  previous=$current
  current=$next
  next=$file
  echo $previous \| $current \| $next 
  #process item
done
previous=$current
current=$next
next=
echo $previous \| $current \| $next 
#process last item