Split file into separate files using pattern

text processing

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:

awk '{
        if(/@File_Version:/){k=$0;}
        else{k=k"\n"$0}
     } 
    /^#Name/{n=$2}
    /EOD/{
        print k > n".txt"; 
    }' file 

Explanation

  • if(/^@File_Version:/){k=$0;} : if this line starts with @File_Version:, save the line as k.
  • else{k=k"\n"$0} : for all other lines, add a newline (\n) followed by the current line to the current value of k.
  • /^#Name/{n=$2} : if this line starts with #Name, set the variable n to the second field (the name).
  • /^EOD/{print k > n".txt";} : if this line starts with EOD, print the variable k (which now contains the entire record) into a file called n.txt where n is the name saved in the previous step.
Related Question