Shell Printf command , a little more dynamic..

A big hello to everyone tagged to this site of knowledge . This is the first post of mine and I am looking forward to an enjoyable stint in this forum where I get to know a lot of new ideas and share whatever knowledge (its not much though :slight_smile: ) I have acquired throughout my career so far with y'all.

To start of , I am , in a sort of stuck in a strange situation.
The requirement is to format a string to a precision , which is will be dynamic .

Lets say the string's 976461 , and we have to format it to a precision of 10 , and LEFT PAD it with zero's. So the output would be 0000976461 .

What I did is to store the precision in a Shell variable (say a ) using the following code :

a=10

and the string in another Shell variable b using :

b=976461

and use the printf command to format the string to the precision stored in variable a , and finally write the output to variable c using

c=` printf "%0'$a'd" $b`

Now , when I echo the value of c, it showing 000976,461.

Can anyone help me with this ?

Thanks
Kumarjit.

Is this exactly how you wrote it? My shell gives an error due to the quoting. Which shell are you using? This works in dash, a mostly posix sh:

$ a=10 b=976461
$ c=$(printf "%0${a}d" "$b")
$ echo "$c"
0000976461

Or:

c=$(printf "%0*d" "$a" "$b")
1 Like

Thanks a ton to you both ( neutronscott and Scrutinizer ), you guys got crazy skills .....

BTW, I am using Korn Shell.

To be very honest , I havent been into Shell scripting for a long period of time, but am keen to know how each of yours codes work .

@neutronscott----firstly what does ${a} in the expression "%0${a}d" stand for , and how different is it from using a blatant "%0$ad" or something like "%0'$a'd"
What I meant to ask is the significance of the {} while invoking a shell variable ?

@Scrutinizer---- I have to admit I dont even have any questions to ask BECAUSE I COULDNT MAKE THE HEADS OR TAILS OF WHAT YOU WROTE, but it works magic .
Could you please explain what your code does and the significance of "*" in the printf command ?

Thank you guys,
Kumarjit.

Hi Kumar, from man printf:

So

printf "%0*d" 10 "$b"

works like

printf "%010d" "$b"
1 Like