Anthony Mellor
asked on
AWK: Am I duplicating the comma delimiter in this code?
This snippet started out life as the answer to (I think) my very first question about AWK
The above works (here, today).
My question is, given the OFS="," seems to be redundant as all the commas reappear in the output, why are they not replaced by spaces when I omit OFS=","
and
if I omit the "," in the print strings, why does AWK not put them in for me given I have specified OFS="," ?
anthony
macosx 10.12.3 yosemite awk version 20070501
BEGIN{FS=",";OFS=","}(NR == 1){print$0",ACCYR,Month,ACCMTH"}(NR!=1){print($0)","substr($1,1,4)","substr($10,4,2)","substr($1,1,4)*12+substr($10,4,2)}
The above works (here, today).
My question is, given the OFS="," seems to be redundant as all the commas reappear in the output, why are they not replaced by spaces when I omit OFS=","
and
if I omit the "," in the print strings, why does AWK not put them in for me given I have specified OFS="," ?
anthony
macosx 10.12.3 yosemite awk version 20070501
ASKER
I made it one print string so as to avoid creating a new line in the output file for each one, it's a workaround. I haven't tried your above yet.
ASKER
MacPro:2_Original_Data_ ADM$ awk BEGIN{FS=",";OFS=","}(NR==1){print $0,"ACCYR","Month","ACCMTH"}(NR!=1){print $0,substr($1,1,4),substr($10,4,2),substr($1,1,4)*12+substr($10,4,2)} in.txt > out.txt
-bash: syntax error near unexpected token `('
MacPro:2_Original_Data_ ADM$
I can't see any missing brackets..
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks
In the new columns you are adding you are actually adding in the comma delimiter yourself and writing one long concatenated string of the multiple column data. So again, one field, OFS not relevant. OFS would be used and important if you did not hard code the commas into the print() statements the way you did, and this is preferable since it allows for easier change of the delimiter later if needed. And may be more efficient since a lot of string concatenation isn't being done.
Open in new window
~bp