OFS does not apply to few records in awk

Hi ,

I am having a problem with my awk oneliner , which for some reason leaves the first two records

Input File

$ cat file1
A1:B1:C1:NoLimit
M1:M2:M3:Limit
A2:B2:C2,C3,C4,C5
A3:B3:C3,C4,C5,C6,C7

Desired output

A1,B1,C1,NoLimit
M1,M2,M3,Limit
A2,B2,C2
,,,C3
,,,C4
,,,C5
A3,B3,C3
,,,C4
,,,C5
,,,C6
,,,C7

I am using the below oneliner to achieve it partially but i dont get why the first two records OFS does not change to comma ,

nawk 'BEGIN{FS=":";OFS=","}{gsub(",","\n,,,",$NF);print}' file1

This gives me an output

A1:B1:C1:NoLimit
M1:M2:M3:Limit
A2,B2,C2
,,,C3
,,,C4
,,,C5
A3,B3,C3
,,,C4
,,,C5
,,,C6
,,,C7

Can someone please help me understand the problem and correct the code

Try: ..);$1=$1;print

In the first two lines there are no commas in the last field, so no substitution takes place and the field does not get modified and therefore the record does not get recalculated and so FS does not get replaced by OFS.

1 Like

Wow!!! , It worked , Can you please explain the logic behind it ?

I had added a bit of explanation to my post. By adding $1=$1 (assigning $1 onto itself) you force the record to be recalculated..

Thanks i got your explanation , but i am confused with awk basics,

nawk 'BEGIN{FS=":";OFS=","}{print}' file1

Should not awk make the changes of the : to , , but i see that didnt happen. So does that mean awk will update the OFS only when it sees some change done to a record ?

It doesn't alter the input line at all unless you do something to one of the tokens.

If that's all you want, awk is overkill anyway, try tr ':' ',' < inputfile > outputfile