Add thousands separator in a number
bash
's printf
supports pretty much everything you can do in the printf
C function
type printf # => printf is a shell builtin
printf "%'d" 123456 # => 123,456
printf
from coreutils will do the same
/usr/bin/printf "%'d" 1234567 # => 1,234,567
With sed
:
$ echo "123456789" | sed 's/\([[:digit:]]\{3\}\)\([[:digit:]]\{3\}\)\([[:digit:]]\{3\}\)/\1,\2,\3/g'
123,456,789
(Note that this only works for exactly 9 digits!)
or this with sed
:
$ echo "123456789" | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'
123,456,789
With printf
:
$ LC_NUMERIC=en_US printf "%'.f\n" 123456789
123,456,789
You can use numfmt:
$ numfmt --grouping 123456789
123,456,789
Or:
$ numfmt --g 123456789
123,456,789
Note that numfmt is not a POSIX utility, it is part of GNU coreutils.