jcrshankar
jcrshankar

Reputation: 1196

Format a number with thousands separators in shell/awk

awk -F, '
{ 
   printf("    Code %s  %s\n",$1,$2)
   r[NR] = $1
   c[NR] = $3
}

END { for(i = 1; i <= NR; i++) printf("  %s Record Count   %s\n", r[i],c[i])

}' totalsum.txt

this is my input file

17,123456,1
16,1234,2
0211,34567,2
21,2345,2

am getting output like below.,

Code   17  123456
Code   16  1234
Code 0211  34567
Code   21  2345
17 Record Count   1
16 Record Count   2
0211  Record Count  2
21 Record Count   2

I need format the output like.,below representing the values with ,

Code   16  1,234
Code 0211  34,567
Code   21  112,345
17 Record Count   1
16 Record Count   2
0211  Record Count  2
21 Record Count   2

could some one please help me.

Upvotes: 1

Views: 3823

Answers (1)

rob mayoff
rob mayoff

Reputation: 386018

You need to use %'d instead of %s as the format specifier if you want thousands separators. Since you're passing the awk script on the command line, getting the quotes right can be tricky. With a hat tip to Ed Morton, here's one way to do it:

#!/bin/sh
awk -F, '
{ 
   printf("    Code %s  %\047d\n",$1,$2)
   r[NR] = $1
   c[NR] = $3
}

END { for(i = 1; i <= NR; i++) printf("  %s Record Count   %s\n", r[i],c[i])

}' totalsum.txt

Output:

$ ./test.sh
    Code 37  123,456
    Code 27  1,234
    Code 0367  34,567
    Code 41  2,345
  37 Record Count   1
  27 Record Count   2
  0367 Record Count   2
  41 Record Count   2

Upvotes: 8

Related Questions