user4829733
user4829733

Reputation: 23

read previous line using bash

Using a while loop, I'm reading a file, lets say:

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

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

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? Is there a way to read previous line or "reset" my read pointer, go backwards?

Upvotes: 0

Views: 1980

Answers (2)

ABHIShek
ABHIShek

Reputation: 34

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.

Upvotes: 0

Yuji
Yuji

Reputation: 525

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

Upvotes: 3

Related Questions