I am trying to convert a number to a string in awk. I would like my string to be left-padded with zeros. E.g., 3 would become "00000003". I have the following test case:
gawk 'BEGIN { CONVFMT = "%08d" ; a = 233 ; print ""a }'
233
It prints "233" not "00000233". Replacing a = 233 with a = 233.0 doesn't change anything. However, replacing a = 233 with a = 233.1 changes everything, and my one-liner correctly prints padded string:
gawk 'BEGIN { CONVFMT = "%08d" ; a = 233.1 ; print ""a }'
00000233
What am I missing ???
CONVFMT
is not used here. In the gawk manual it says:
As a special case, if a number is an integer, then the result of converting it to a string is always an integer, no matter what the value of CONVFMT may be. Given the following code:
CONVFMT = "%2.2f" a = 12 b = a ""
b has the value "12", not "12.00".
It wouldn't print 00000233 even if 233.0 was used:
$ gawk 'BEGIN { CONVFMT = "%08d" ; a = 233.0 ; print ""a }'
233
You should use sprintf
to achieve what you want:
$ gawk 'BEGIN { a=233; name=sprintf("%08d",a); print name }'
00000233
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With