Operating System - HP-UX
1833012 Members
3171 Online
110048 Solutions
New Discussion

Using printf in awk to produce comma-seperated output

 
Viji Parthasarathy
New Member

Using printf in awk to produce comma-seperated output

I wrote the following in AWK
awk '{printf("%'d\n",100000)}'
to get 100,000
I get an error - syntax error at line 1 : `"' unmatched
I undestand that there is a setlocale function which can be used in C to get this comma-seperated output. How do I achieve it in awk.
Thanks in advance
5 REPLIES 5
harry d brown jr
Honored Contributor

Re: Using printf in awk to produce comma-seperated output


{ printf("%-12s %20s\n", $0, addcomma($0)) }

function addcomma(x, num) {
if (x < 0)
return "-" addcomma(-x)
num = sprintf("%.2f", x) # num is dddddd.dd
while (num ~ /[0-9][0-9][0-9][0-9]/)
sub(/[0-9][0-9][0-9][,.]/, ",&", num)
return num
}

Live Free or Die
A. Clay Stephenson
Acclaimed Contributor

Re: Using printf in awk to produce comma-seperated output

Hi:

Unfortunately the ' modifier does not work in awk like it does in printf(3C). It took me a few minutes to find an awk script that had the function in it. I've attached fmtint.

Use it like this:
printf("%s",fmtint(myvar))

it will convert 98712 --> 98,712

Clay

If it ain't broke, I can fix that.
Viji Parthasarathy
New Member

Re: Using printf in awk to produce comma-seperated output

Thanks for your reply. Right now I am using a
function similar to the one which you have suggested but want to know is there is any other way.
harry d brown jr
Honored Contributor

Re: Using printf in awk to produce comma-seperated output

I forgot to add the contributor of the addcomma routine:

http://www.netlib.org/research/awkbookcode/ch3
Live Free or Die
A. Clay Stephenson
Acclaimed Contributor

Re: Using printf in awk to produce comma-seperated output

I rather doubt it though you might try to download gawk. Unlike C, since awk is interpreted it would have a very difficult time correctly parsing the ' character especially when quoted in the shell as well.
If it ain't broke, I can fix that.