How to use Awk to format numbers with a thousands separator

awktext formattingtext processing

Can anyone tell me how to use the awk command for this statement "the number will contain commas after every three digits. For example, 100000000 will become 100,000,000."

I know how to use sed command to obtain this output but I don't know how to use awk, I'm beginner please tell me I'm searching from morning but I didn't get a suitable answer for this so please suggest me best tutorials for learning.

sed command to get the above output:

echo "100000000" | sed -E 's/([0-9]{3})/,\1/2g'

Best Answer

A locale-independent solution with manual formatting

This should work on any POSIX-compatible OS regardless of the locales installed.

$ printf "1\n10\n100\n1000\n10000\n100000\n1000000\n10000000\n100000000\n" \
| awk '{ len=length($0); res=""; for (i=0;i<=len;i++) { res=substr($0,len-i+1,1) res; if (i > 0 && i < len && i % 3 == 0) { res = "," res } }; print res }'
1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000

A solution that uses printf and the en_US locale.

The printf sequence %'d prints a decimal integer formatted with the current locale's thousands separator.

$ printf "1\n10\n100\n1000\n10000\n100000\n1000000\n10000000\n100000000\n" \
| LC_ALL=en_US.UTF-8 awk '{ printf("%'"'"'d\n", $0) }'
1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000
Related Question