Padding zeros in a string

前端 未结 7 619
情话喂你
情话喂你 2020-12-24 10:03

I\'m writing a bash script to get some podcasts. The problem is that some of the podcast numbers are one digits while others are two/three digits, therefore I need to pad t

7条回答
  •  不知归路
    2020-12-24 10:59

    Attention though if your input string has a leading zero!
    printf will still do the padding, but also convert your string to hex octal format.

    # looks ok
    $ echo `printf "%05d" 03`
    00003
    
    # but not for numbers over 8
    $ echo `printf "%05d" 033`
    00027
    

    A solution to this seems to be printing a float instead of decimal.
    The trick is omitting the decimal places with .0f.

    # works with leading zero
    $ echo `printf "%05.0f" 033`
    00033
    
    # as well as without
    $ echo `printf "%05.0f" 33`
    00033
    

提交回复
热议问题