How to concatenate all 5 rows if column 2 equals a certain value?

advertisements

I have a file that if the second column has the number 2, I want to concatenate the next 5 lines, for example:

67 2
a b c
a b
0.1 0.2 0.3 0.4
0.3 0.9 0.7 0.1
09 3
b v c
5 6 7 8
78 2
p o p
q d
1.0 0.9 0.8 0.7
0.4 0.3 0.2 0.1

The output should be:

67 2 a b c a b 0.1 0.2 0.3 0.4 0.3 0.9 0.7 0.1
78 2 p o p q d 1.0 0.9 0.8 0.7 0.4 0.3 0.2 0.1


awk solution: To concatenate 5 lines (including pattern line) on each encountering the line with 2 in its 2nd column (excepting lines concatenated):

awk '$2==2{i=4;tail=$0; while (i-- && (getline nl) > 0) { tail=tail FS nl } print tail}' file

The output:

67 2 a b c a b 1 2 3 4 0 9 7 1
78 2 p o p q d 0 9 8 7 4 3 2 1