willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476689

Iterate over two items in bash

Given a file integers that contains integers separated by new lines. For instance:

1
39
77
109
137
169
197
229
261
293

One can iterate over the file using the following code:

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

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:

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

results in:

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

Upvotes: 0

Views: 84

Answers (2)

konsolebox
konsolebox

Reputation: 75488

{
    read a
    while read b; do
        echo "$a | $b"
        a=$b
    done
} < file

Output:

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

Upvotes: 4

P.P
P.P

Reputation: 121397

Use a variable to store the previous value:

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

Upvotes: 4

Related Questions