Description
Given a datafile of lines and a tag, say 01,. Some lines of that file begin with that tag, while the others don't. If a line does not begin with that tag, append it to the nearest and preceding one beginning with that tag.
Raw Input Desired Output
01,89,4,438,
99,,109,005,,,697,
23,564,,
01,855,044,953,
45,,100,078,,,006,,
01,987,654,321,
01,84,,,203,570,
67,,13,492,,
01,23,456,7890,
01,89,4,438,99,,109,005,,,697,23,564,,
01,855,044,953,45,,100,078,,,006,,
01,987,654,321,
01,84,,,203,570,67,,13,492,,
01,23,456,7890,
Script and Comments
Script1
[ 1] :loop
[ 2] N
[ 3] /\n01,/{
[ 4] P
[ 5] D
[ 6] }
[ 7] s/\n//
[ 8] b loop
Comments
  1. The Pattern Space is abbreviated to `PS'.
  2. This script assumes that the first line of the datafile begins with 01,.
  3. This script consists of a loop:
    • Append the next line to the end of PS by command `N' of Step [2],
    • If the line read by Step [2] begins with 01,, then PS has two lines now and each of them begins with 01,. Steps [4] and [5] are used to print the first one, deletes it and starts a new cycle.
    • Otherwise, Step [7] is used to remove the separating newline, Step [8] makes sed branch to Step [1].
  4. When performing command `N' on the last line of a file, GNU sed prints the contents of PS then terminates.
Script2
[ 1] N
[ 2] /\n01,/P
[ 3] /\n01,/!s/^\(.*\)\n/\n\1/
[ 4] D
Comments
  1. A neat version.