Execute a command for 3 lines at a time

0

I'm trying to run three separate processed while reading foo.txt

Here is the example:

cat foo.txt | while read line
do
echo line1
echo line2
echo line3
echo ""
done

The expected output is:

line1
line2
line3

line4
line5
line6

line7
line8

and continues like this. This is just an example. I want to execute some other commands…

The KingMaker

Posted 2014-01-05T06:20:09.353

Reputation: 103

Please check your formatting. Your post used code formatting all over the place. Also it'd help if you showed some real example rather than something contrived. – slhck – 2014-01-05T08:34:19.053

Please explain what you actually want to do. Do you want to split a file into groups of three lines and run a different command on the 1st 2nd and 3rd line of each group? – terdon – 2014-01-05T11:19:01.137

Answers

2

while true
do
    read line1 || break
    read line2 || break
    read line3 || break
    echo $line1
    echo $line2
    echo $line3
    echo ""
done <foo.txt

This produces the output:

line1
line2
line3

line4
line5
line6

line7
line8
line9

To program defensively, we should allow for files whose total number of lines is not a multiple of three. In that case, to make sure that every line gets processed:

while true
do
    read line1 || break
    echo $line1
    read line2 || break
    echo $line2
    read line3 || break
    echo $line3
    echo ""
done <foo.txt

John1024

Posted 2014-01-05T06:20:09.353

Reputation: 13 893

I think you should put the echo right after the read, otherwise if line1 was read and line2 not, the echo $line1 will not be executed – Eran Ben-Natan – 2014-01-05T08:27:37.750

@EranBen-Natan Good suggestion. Answer updated. – John1024 – 2014-01-05T08:37:30.757

2

$ awk '1; NR%3==0 { print "" }' foo.txt

Quite the same but on pure Bash:

NR=0
while read line; do
    echo "$line" 
    (( ++NR % 3 == 0 )) && echo
done < foo.txt

And I really wonder why do you need this.

Dmitry Alexandrov

Posted 2014-01-05T06:20:09.353

Reputation: 984