Selectively Reformating a file using AWK

Dear users,

I am new to AWK and have been battling with this one for close to a week now. Some of you did offer some help last week but I think I may not have explained myself very well. So I am trying again.

I have a dataset that has the following format where the datasets repeat every three lines. So the headings come first and then the packets of data are written out in the file in a similar manner.

col1 col2 col3
col4 col5 col6
col7 col8 col9
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24
25 26 27

and I need to change it to the format below:

col1 col2 col3 col4 col5 col6 col7 col8 col9
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27

Now if that weren't bad enough. Say I only wanted the data from col2, col5 and col8. Or I wanted to select the data from any other column and only that column to be printed out? How would I do this please? The data pattern is regular and repeats itself and I could find out how many lines the file has in total if need be.

Thanks in advance.

Regards,

sda_rr

here's the first part:

nawk 'ORS=FNR%3?FS:RS' myFile

# default fields '2 5 8'
nawk -f sda.awk myFile

# specified fields: '1 3 9'
nawk -v fld='1 3 9' -f sda.awk myFile

sda.awk:

BEGIN {
  fld=(fld=="")? "2 5 8":fld
  n=split(fld, a, FS)
}
{
     rec=(rec=="")?$0:rec OFS $0
}
!(FNR%3){
     rN=split(rec, recA, OFS)
     rec=""
     for(i=1; i<=n; i++)
       printf("%s%c", recA[a], (i==n) ? ORS : OFS)
}

Thanks very much but you lost me here!!

What do you mean exactly by default and specified fields? If you specify the fields, does it oiverride the default?

Thanks.

# default fields '2 5 8'
nawk -f sda.awk myFile

# specified fields: '1 3 9'
nawk -v fld='1 3 9' -f sda.awk myFile

yes, that's right - try it and see.
In the future please use BB Code tags when giving data and/or code samples - you'll be increasing your chances of your questions being answered.

Thanks very much for your help. I think I can run with that.

Best Regards,

sda_rr