【问题标题】:Bash for loop get previous and next itemBash for循环获取上一个和下一个项目
【发布时间】:2012-11-19 11:45:48
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

    • 使用* 代替`ls`
    【解决方案2】:
    declare -a files=(*)
    for (( i = 0; i < ${#files[*]}; ++ i ))
    do
      echo ${files[$i-1]} ${files[$i]} ${files[$i+1]}
    done
    

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

    【讨论】:

    • 我的 bash 不包含第一个 -1 或最后一个 +1。
    • last+1 不会被包装。 first-1 应该是,可能是您的 bash 版本旧,它适用于 bash 版本 4。
    • 我误读了 +1 案例。我的 bash 是 CentOS 6.3 提供的 4.1.2(1)。在包含文件 a、b、c 的目录中运行脚本会产生以下输出: a b\n a b c\n b c\n
    猜你喜欢
    • 2021-06-08
    • 2023-02-09
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2021-04-26
    相关资源
    最近更新 更多