Printable Version of Topic

Click here to view this topic in its original format

Linuxhelp _ Programming in Linux _ AWK

Posted by: Larry Mar 29 2008, 05:35 PM

I'm trying to add a column of numbers which contain commas in a file called countries.txt; i.e, 123,456. The numbers are in the 2nd column of the file. The general structure of the command is:

awk '(tot+=$2); END {print "Total = " tot} countries.txt

When I execute this all I get is the sum of the numbers prior to the first comma. I know that I have to either parse the numbers or somehow get rid of the commas.

Can anyone tell me how to do this. Thanks.

Larry

Posted by: markjr Mar 30 2008, 09:08 AM

You could rinse out the commas before it ever hits awk:

sed 's/,//g' | awk .....

Or maybe specify the input field separator in the BEGIN section of the awk script itself, which I think is

BEGIN { IFS=" " }

(or whatever non-comma field separates your columns)

-mark


QUOTE (Larry @ Mar 29 2008, 05:35 PM) *
I'm trying to add a column of numbers which contain commas in a file called countries.txt; i.e, 123,456. The numbers are in the 2nd column of the file. The general structure of the command is:

awk '(tot+=$2); END {print "Total = " tot} countries.txt

When I execute this all I get is the sum of the numbers prior to the first comma. I know that I have to either parse the numbers or somehow get rid of the commas.

Can anyone tell me how to do this. Thanks.

Larry

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)