Rearrange text file by prepending data rows with header row

awkgrepsedtext processing

I have a file whose content looks like this:

2009 150  0  0  0     0000
75.316   0.0400390625  0.00007        0.00000 0.8980
76.216   0.0400390625  0.00007        1.00000 0.9046
77.217   0.0400390625  0.00009        2.00000 0.9113
78.341   0.0400390625  0.00010        3.00000 0.9183
2009 150  2  0  0     0000
75.316   0.0400390625  0.00007        0.00000 0.8980
76.216   0.0400390625  0.00007        1.00000 0.9046
77.217   0.0400390625  0.00009        2.00000 0.9113
78.341   0.0400390625  0.00010        3.00000 0.9183
79.616   0.0400390625  0.00013        4.00000 0.9255

I would like to:

  1. Find all lines that start with keyword 2009.
  2. Pre-pend those lines to all following ones until another occurrence of line that starts with 2009 is found, and so on until EOF.

In essence I am looking for an output like this:

2009 150  0  0  0     0000 75.316   0.0400390625  0.00007        0.00000 0.8980
2009 150  0  0  0     0000 76.216   0.0400390625  0.00007        1.00000 0.9046
2009 150  0  0  0     0000 77.217   0.0400390625  0.00009        2.00000 0.9113
2009 150  0  0  0     0000 78.341   0.0400390625  0.00010        3.00000 0.9183
2009 150  2  0  0     0000 75.316   0.0400390625  0.00007        0.00000 0.8980
2009 150  2  0  0     0000 76.216   0.0400390625  0.00007        1.00000 0.9046

…….

I have been scratching my head on this for quite a while and cannot come up with a solution. Help would be appreciated. I know how to extract the text between keywords using flags but I am not sure if that is the right direction.

Best Answer

You can use awk for this:

awk '/^2009/{a=$0;next}{print a" "$0} ' file.txt

This will only prepend a space to any lines before the first match of 2009, you can set a default string to prepend like this:

awk 'BEGIN{a="My default prepend string";}/^2009/{a=$0;next}{print a" "$0} ' file.txt
Related Question