Thousands separator in printf in zsh

numeric dataprintfzsh

I have been trying to define a thousands separator in printf for a while now and I have discovered that zsh has some problems with it.

In bash I can use something like:

$ printf "%'d\n" 1234567890
1,234,567,890

but in zsh it won't work :

$ printf "%'d\n" 1234567890
printf: %': invalid directive

I have just found out that coreutils printf will do it just fine:

$/usr/bin/printf "%'d\n" 1234567890
1,234,567,890

How can I use thousands separator in zsh?

$ zsh --version
zsh 5.0.2 (x86_64-pc-linux-gnu) 

Best Answer

Update: as of zsh v. 5.1, the printf builtin supports grouping of thousands via ' just like bash/coreutils printf (see also the discussion here).


The thousands separator is a GNU extension that zsh doesn't support, and it has its own printf builtin that you end up using instead. As mentioned in the linked post, you can get the locale-dependant thousands separator with:

zmodload zsh/langinfo
echo $langinfo[THOUSEP]

If you need to use zsh specifically and exclusively, you can use that with sed.

Probably easier will be to use the non-builtin printf from GNU coreutils instead, which will permit the thousands separator option if your system does:

$ command printf "%'d\n" 1234567890
1,234,567,890

command printf tells the shell not to use a builtin or alias, but to look up the command in $PATH.