Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make awk add correctly when commas are used as digit group separators

Tags:

bash

awk

I'm trying to use awk to add up the numbers from an output file, but it seems awk doesn't understand the commas separating the thousands.

For example, running

awk '{if($1=="foo") {SUM+=$2}}END{print "foos ",SUM}'

on

foo 70.31
foo 125.00
foo 1,750.00

returns

foos 196.31

What's the best/appropriate way in awk to add these up correctly?

like image 691
a113nw Avatar asked Nov 27 '25 09:11

a113nw


1 Answers

awk '{if($1=="foo") {gsub(",", "", $2); SUM+=$2}}END{print "foos ",SUM}'

Or, if you don't want to clobber $2:

awk '{if($1=="foo") {TERM=$2; gsub(",", "", TERM); SUM+=TERM}}END{print "foos ",SUM}'
like image 64
Keith Thompson Avatar answered Nov 29 '25 03:11

Keith Thompson