0

I am trying to change the code of someone else. Can anyone explain this line of code to me?

xs=`printf "%.*d" 3 $x`

The $x is the loop variable, I do understand that.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Baloo
  • 223
  • 4
  • 17
  • Aside: If this is modern bash, `printf -v xs '%.*d' 3 "$x"` would be the more efficient way to write this, avoiding the performance overhead of a subshell. – Charles Duffy May 18 '15 at 16:19

2 Answers2

4

The .* is a way to pad the format. From Bash-hackers #The printf command:

The precision for a floating- or double-number can be specified by using ., where is the number of digits for precision. If is an asterisk (*), the precision is read from the argument that precedes the number to print, like (prints 4,3000000000):

printf "%.*f\n" 10 4,3

So by saying

xs=`printf "%.*d" 3 $x`

$xs is getting the number stored in $x with three digits of precision. Note also that it is best to use $() and also to quote the parameter:

xs=$(printf "%.*d" 3 "$x")

See some examples:

$ printf "%.*d\n" 3 1
001
$ printf "%.*d\n" 3 1234
1234

There is a better reference of man printf, thanks to Aaron Digulla for pointing it in the comments:

The precision

An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. (...)

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    In this case, it's not precision (which would be after the comma) but padding. – Aaron Digulla May 05 '15 at 13:25
  • @AaronDigulla you are right. However, I cannot find the proper documentation reference ([and it seems to be a common problem!](http://unix.stackexchange.com/q/84148/40596)) – fedorqui May 05 '15 at 13:35
  • 1
    Actually, you're right. http://linux.die.net/man/3/printf explains it. `*` would be "width" but `.*` is called "precision". It's usually used for floating point numbers but it also works for integers: "This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions[...]" – Aaron Digulla May 06 '15 at 12:07
  • 1
    `man printf` isn't necessarily the best resource to use here, since one's shell may provide a version of printf with more/better facilities than the built-in one. Thus, `help printf` is arguably the better resource; the bash-hackers page is also great. – Charles Duffy May 18 '15 at 16:20
2

It's displaying an integer with a 0 padding for a size of 3 characters.

$ x=4
$ printf "%.*d" 3 $x
004

$ x=12
$ printf "%.*d" 3 $x
012

$ x=9999
$ printf "%.*d" 3 $x
9999
Blusky
  • 3,470
  • 1
  • 19
  • 35