Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number to string conversion with padding in awk

Tags:

awk

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 ???

like image 357
Artur P Avatar asked Aug 01 '21 16:08

Artur P


1 Answers

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
like image 75
Arkadiusz Drabczyk Avatar answered Nov 20 '22 08:11

Arkadiusz Drabczyk