简体   繁体   English

使用 bash 读取上一行

[英]read previous line using bash

Using a while loop, I'm reading a file, lets say:使用 while 循环,我正在读取一个文件,可以说:

string1
string2
string3
string4
string5
string6

What is happening is because I read string1 and string2 in the first iteration of my while loop, the second iteration starts on string3, the third iteration starts in string5...ect发生的事情是因为我在 while 循环的第一次迭代中读取了 string1 和 string2,第二次迭代从 string3 开始,第三次迭代从 string5 开始......等等

I've tried looking for possible flags which read may have, doesnt seem like this is the case.我已经尝试寻找读取可能具有的可能标志,但情况似乎并非如此。 I've also tried $Line1=$Line2 hoping I can specify which line I would like to read我也试过 $Line1=$Line2 希望我可以指定我想读哪一行

Here is what my loop looks like...这是我的循环的样子......

while read line1
do
  read line2
done

I read string1 and string2 in the first iteration of the loop, in my second iteration i would like to read string2 and string3 of the loop, 3rd iteration string3 and string4 of the loop ect.....Is there a way to specify which line I would like to read?我在循环的第一次迭代中读取了 string1 和 string2,在我的第二次迭代中我想读取循环的 string2 和 string3,第三次迭代的循环 string3 和 string4 等等.....有没有办法指定哪个行我想读? Is there a way to read previous line or "reset" my read pointer, go backwards?有没有办法读取上一行或“重置”我的读取指针 go 向后?

You can do it by storing the previous line.您可以通过存储上一行来做到这一点。

#!/bin/bash
prev=
while read line
do
    if [ ! -z "${prev}" ];then
        line1="${prev}"
        line2="${line}"
        echo "${line1}  ${line2}"
    fi
    prev="${line}"
done
string1  string2
string2  string3
string3  string4
string4  string5
string5  string6

You can try this by storing all file in an array.您可以通过将所有文件存储在数组中来尝试此操作。

#!/bin/bash
b=(`cat filename`)
for i in $(eval echo {0..$[${#b[@]}-2]})
do
echo "${b[i]} ${b[i+1]}"
done

here echo ${#b[@]} returns the length of array.这里echo ${#b[@]}返回数组的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM