Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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) 
share|improve this question

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer
3  
I suggest command printf instead of /bin/printf, which is not portable. –  jofel Jul 2 at 9:46
    
@jofel What is command printf? –  Patryk Jul 2 at 9:48
    
Good point! I've edited that in. @Patryk, it skips builtins and looks up the command as though the shell weren't shadowing it. –  Michael Homer Jul 2 at 9:49
1  
@Patryk commmand forces the shell to use external commands and not any built-in commands (like printf, time, ...). More or less the opposite is the command builtin. –  jofel Jul 2 at 9:51
    
Ok, cool. Where can find some docs on that? –  Patryk Jul 2 at 9:52

To complement Michael's answer, you could do the thousand-sep formatting by hand with zsh operators with:

var=1234567

zmodload zsh/langinfo
setopt extendedglob
echo $var[1,(l=-($#var-1)/3*3)-1]${var[l,l?-1:l]//(#m)???/$langinfo[THOUSEP]$MATCH}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.