printf, awk ... How to format a number with space to the thousands

With some printf implementations (including GNU printf and the printf builtin of ksh93, zsh, bash and lksh (but not dash nor yash) on GNU systems) and assuming your system has a French (of France or Canada at least), or Swedish or Slovenian or Macedonian or Kyrgyz locale (and a few more, that is, those that have space as the thousand separator):

$ LC_ALL=fr_FR locale -k thousands_sep
thousands_sep=" "
$ LC_ALL=fr_FR printf "%'d\n" 10000000000
10 000 000 000

Also works with some awk implementations:

$ LC_ALL=fr_FR awk 'BEGIN{printf "%'\''d\n", 1e10}'
10 000 000 000

You can use LC_NUMERIC instead of LC_ALL if you know LC_ALL is otherwise not set.


You need to loop with sed:

echo "9765625000 * 1024 = 10000000000000" | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1 \2/;ta'
9 765 625 000 * 1 024 = 10 000 000 000 000

(Thank you for the improvement, Stéphane!)

Or better readable, but maybe not compatible with older sed versions, with extended regular expressions:

echo "9765625000 * 1024 = 10000000000000" | sed -E -e :a -e 's/(.*[0-9])([0-9]{3})/\1 \2/;ta'
9 765 625 000 * 1 024 = 10 000 000 000 000

A simple combination of sed and rev could be employed -

echo  "I have 10000013984 oranges" | rev | sed "s/[0-9][0-9][0-9]/& /g" | rev 

first rev is required to replace number from right to left , and the second one for bringing back the original string.