Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing leading zeros

Status
Not open for further replies.

NPI

Programmer
Feb 7, 2001
4
US
How can I get awk to print out the leading zeros when padding a field width?

The command:
awk '
BEGIN{
v_nmbr=1
printf( "%3d\n", v_nmbr )
}
'
outputs 1.
I would like to get 001.
We hope that this helps.

Regards,
NPI
 
I auppose if might be poor forum to answer my own question but I just figured out the answer for integers.

printf( "%.3d\n", v_nmbr ) will yield 001

I suppose that the question still remains on doing this with reals.

i.e what if v_nmbr=1.1?
 
Hey Everyone,

Thanks for your help.

It turns out that the answer is a combination of things I learned here and elsewhere.

To print any number padded with zeros just place a 0 as the first character in the format specifier.
For an integer: %03d
For a real: %03.1f

awk 'BEGIN{v_nmbr=1; printf("%03d\n", v_nmbr )}'
001
awk 'BEGIN{v_nmbr=1.1; printf("%05.1f\n", v_nmbr )}'
001.1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top