Walker News

Uses Awk To Print Thousand Separator For Numeric Value

Question: How to use awk to format numeric output with a thousand-separator character (e.g. the comma character)?

There is a awk syntax for inserting comma as thousand-separator to a numeric value, but the syntax is only effective when a proper Linux locale is used. As shown by the screenshot, you can either set the locale environment variable or specify the locale setting during awk runtime:

Using awk to format numeric value with a thousand-separator character.

During my test on RHEL 6.3, the interactive Linux command prompt is by default having “LANG=en_US.UTF-8”, so the awk works perfectly without specifying the LANG or LC_ALL setting.
Run locale at Linux command prompt to check the Linux locale settings.

It fails, however, when it’s running as a cronjob (scheduled task running in background), because both LANG and LC_ALL values are null in the cronjob environment. To fix it, you can write the awk in either one of these ways:
export LC_ALL=en_US.UTF-8
echo "2013" | \
 awk '{printf "Size: %'\''d\n",$0}'

OR,
echo "2013" | \
 LC_ALL=en_US.UTF-8 awk '{printf "Size: %'\''d\n",$0}'

The result is
Size: 2,013

With reference to GNU awk manual. Happy scripting! :)

Custom Search

2016  •  Privacy Policy