I need to split a file (see sample) into separate files. Each new file shall inherit the name in line 7 i.e. SAMPLE1.txt
, SAMPLE2.txt
etc.
@File_Version: 4
@Coordinate_Type_is: 1
@Export_Type_is: 1
@Number_of_P: 1
@T_Type_Name: ,
#File_Version____________-> 4
#Name____________-> SAMPLE1
#Type____________-> 3
#End_of_file_header
000000.00000 0000000.00000 0000.00000
000000.00000 0000000.00000 0000.00000
...
EOD
@File_Version: 4
@Coordinate_Type_is: 1
@Export_Type_is: 1
@Number_of_P: 1
@T_Type_Name: ,
#File_Version____________-> 4
#Name____________-> SAMPLE2
#Type____________-> 3
#End_of_file_header
000000.00000 0000000.00000 0000.00000
000000.00000 0000000.00000 0000.00000
...
EOD
@File_Version: 4
@Coordinate_Type_is: 1
@Export_Type_is: 1
@Number_of_P: 1
@T_Type_Name: ,
#File_Version____________-> 4
#Name____________-> SAMPLE3
#Type____________-> 3
#End_of_file_header
000000.00000 0000000.00000 0000.00000
000000.00000 0000000.00000 0000.00000
...
EOD
Best Answer
You could do this with
awk
:Explanation
if(/^@File_Version:/){k=$0;}
: if this line starts with@File_Version:
, save the line ask
.else{k=k"\n"$0}
: for all other lines, add a newline (\n
) followed by the current line to the current value ofk
./^#Name/{n=$2}
: if this line starts with#Name
, set the variablen
to the second field (the name)./^EOD/{print k > n".txt";}
: if this line starts withEOD
, print the variablek
(which now contains the entire record) into a file calledn.txt
wheren
is the name saved in the previous step.