在 shell/awk 中用千位分隔符格式化数字

Format a number with thousands separators in shell/awk

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

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

}' totalsum.txt

这是我的输入文件

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

我得到如下输出。,

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

我需要格式化输出,如下所示,用 ,

表示值
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

有人能帮帮我吗

如果您需要千位分隔符,您需要使用 %'d 而不是 %s 作为格式说明符。由于您是在命令行上传递 awk 脚本,因此正确使用引号可能很棘手。向 Ed Morton 致敬,这是一种方法:

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

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

}' totalsum.txt

输出:

$ ./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