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…

  • 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 Jan 5 '14 at 8:34
  • 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 Jan 5 '14 at 11:19
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
  • 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 Jan 5 '14 at 8:27
  • @EranBen-Natan Good suggestion. Answer updated. – John1024 Jan 5 '14 at 8:37
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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.