Padding zeros in a string

前端 未结 7 606
情话喂你
情话喂你 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:53

    This is in response to an answer given by cC Xx. It will work only until a's value less is than 5 digits.

    Consider when a=12345678. It'll truncate the leading digits:

    a="12345678" 
    b="00000${a}" 
    c="${b: -5}" 
    echo "$a, $b, $c"
    

    This gives the following output:

    12345678, 0000012345678, 45678
    

    Putting an if to check value of a is less than 5 digits and then doing it could be solution:

    if [[ $a -lt 9999 ]] ; then b="00000${a}" ; c="${b: -5}" ;  else c=$a; fi  
    

提交回复
热议问题