Search code examples
shellawkdesign-patternsgrepmatch

Find a match on a line, and insert this result into each following line until it matches END


I have a file similar to this

NAME : Name1
TYPE : Something2
TEST : Something3
END
NAME : Name2
TYPE : Something5
TEST : Something6
END

All the contents after the ':' are going to be different values

This repeats until the end of the file

I would like to create another file with the output looking like

NAME : Name1
Name1 TYPE : Something2
Name1 TEST : Something3
END
NAME : Name2
Name2 TYPE : Something5
Name2 TEST : Something6
END

Have tried

awk '/NAME/ {print;while($0!~ /END/){getline;print;}}' InputFile > OutputFile

but do not know how to get the Name matches to be inserted as it finds them.

I am using shell script

Any help much appreciated

Terry


Solution

  • One awk idea:

    awk '
    $1=="END"  { pfx = ""     }      # clear prefix
               { $1  = pfx $1 }      # append prefix to 1st field
    $1=="NAME" { pfx = $NF " "}      # define prefix as last field + space
    1                                # print current line
    ' InputFile
    

    This generates:

    NAME : Name1
    Name1 TYPE : Something2
    Name1 TEST : Something3
    END
    NAME : Name2
    Name2 TYPE : Something5
    Name2 TEST : Something6
    END