【问题标题】:Iterate over two items in bash迭代bash中的两个项目
【发布时间】:2014-08-01 12:43:30
【问题描述】:

给定一个文件integers,其中包含由新行分隔的整数。例如:

1
39
77
109
137
169
197
229
261
293

可以使用以下代码遍历文件:

while read a
do
    echo "$a"
done < integers

不过,我正在寻找一种优雅的解决方案,让循环一次接受两个整数,并且总是一步一步更新,这样:

while #some funny commands
do
    echo "$a | $b"
done < integers

结果:

1 | 39
39 | 77
77 | 109
109 | 137
137 | 169
169 | 197
197 | 229
229 | 261
261 | 293

【问题讨论】:

  • @AvinashBabu,@Jayesh:没有那个部分已经工作了。我想遍历一个文件,以便在i-th 迭代中$a 包含i-th 行和$b i+1-th 行。

标签: bash loops


【解决方案1】:
{
    read a
    while read b; do
        echo "$a | $b"
        a=$b
    done
} < file

输出:

1 | 39
39 | 77
77 | 109
109 | 137
137 | 169
169 | 197
197 | 229
229 | 261
261 | 293

【讨论】:

  • 我也是这么想的,但两者都没有给出预期的输出。
  • 但是每次迭代都会读取两个项目。预期的程序应在i-th 迭代中打印i-th 行和i+1-th 行。
  • @Kent 指令I'm looking however for an elegant solution such that the loop takes two integers at once and always updates by one step, such that误导了我。
  • 已更新。而且我的答案不需要经过测试。
【解决方案2】:

使用变量来存储之前的值:

prev= 
while read line; do
   [[ ! -z $prev ]] && echo $prev "|" $line; 
   prev=$line; 
done <file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多