Split file when the key field change !

Hello,

I have the following example data file:

Rv.Global_Sk,1077.160523,D,16/09/2011
Rv.Global_Sk,1077.08098,D,17/09/2011
Rv.Global_Sk,1077.001445,D,18/09/2011
Rv.Global_Sk,1072.660733,D,19/09/2011
Rv.Global_Sk,1070.381557,D,20/09/2011
Rv.Global_Sk,1071.971747,D,21/09/2011
Rv.Global_Sk,1056.547923,D,22/09/2011
Rf.Col_Estabil,568.4547,D,04/01/2000
Rf.Col_Estabil,568.7978,D,05/01/2000
Rf.Col_Estabil,569.0438,D,06/01/2000
Rf.Col_Estabil,569.1829,D,07/01/2000
Rf.Col_Estabil,570.0619,D,11/01/2000
Rf.Col_Estabil,570.2699,D,12/01/2000
Rf.Col_Estabil,570.3019,D,13/01/2000
Rf.Col_Estabil,570.5283,D,14/01/2000

Could you please help me with an awk shell script for split in files when change the first key field to the name of the field plus the .csv extension, for instance Rf.Col_Estabil.csv.

Thanks in advance

Something like this should do what you need:

awk -F , '
{
    if( lastf && $1 != lastf )
        close( lastf );
    lastf = $1;
    printf( "%s\n", $0 ) >lastf ".csv";
}' input-file

where input-file is your original file.

1 Like

For a quick&dirty solution just this should work (in 99.9% cases):

awk -F, '{print > $1 ".csv"}' INPUTFILE
1 Like
$ sed 's,^Rf.Col_Estabil,&.csv,g' infile
1 Like

Jayan_jay,

Thanks a lot for your help. This script working perfect.