Link to home
Start Free TrialLog in
Avatar of Anthony Mellor
Anthony MellorFlag for United Kingdom of Great Britain and Northern Ireland

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

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)}

Open in new window


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
Avatar of Bill Prew
Bill Prew

In your code, $0 will be the exact input line, and if it came in with comma delims then those will transfer to output line. $0 is a single field so OFS not relevant there.

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.

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)}

Open in new window

~bp
Avatar of Anthony Mellor

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.
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$ 

Open in new window


I can't see any missing brackets..
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks