开发者

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

开发者 https://www.devze.com 2023-04-01 20:38 出处:网络
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.

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?


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}'
0

精彩评论

暂无评论...
验证码 换一张
取 消