Split a file into multiple files based on first two digits of file.

Hi ,
I do have a fixedwidth flatfile that has data for 10 different datasets each identified by the first two digits in the flatfile.
01 in the first two digit position refers to Set A
02 in the first two digit position refers to Set B and so on
I want to genrate 10 different files from my fixedwidth file , each file having it's own record set.
File A.dat having only 01 records.
File B.dat having only 02 records and so on.

Please Let me know how we can achieve this.

awk '{ print > substr($0,1,2) ".dat" }' filename1 filename2 filename3 ...

will use the first two characters of each line to print into the corresponding ".dat" file.

Hi Corona,
Thank you very much
this works good but how can I get specific output filename to specific first two digits like
01 will get filename as MEM.dat
02 will get filename as DEPT.dat

also there is requirement where 04 and 05 both go into single file called sale.dat

In that case create an associative array that maps the 2 digits with the desired filename...read/parse each input file record...and output it to the specific filename based on the numerical code.

Like this...

awk 'BEGIN{split("MEM DEPT X SALE SALE",file," ")}{print > file[$1+0]".dat"}' infile1 infile2

--ahamed

Sorry to ask but how to do this.

---------- Post updated at 04:51 PM ---------- Previous update was at 04:42 PM ----------

Thank you Ahmad , this works like a charm..could you please explain me what command is actually doing...

It creates an array "file" with the output file names. file[1]=MEM, file[2]=DEPT etc. The data from the actual file is used as the index for obtaining the file names from this array and print the data.

--ahamed