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.
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.
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. (...)
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