Adding a zero to single digit variable

前端 未结 10 2076
星月不相逢
星月不相逢 2021-01-30 05:31

Trying to add a zero before the varaible if it\'s less than 10 and create said directory. I can\'t seem to get the zero to add correctly. Keeps resulting in making 02.1.20

相关标签:
10条回答
  • 2021-01-30 06:15

    Will this work for you?

    zeroes="0000000"
    pad=$zeroes$i
    echo ${pad:(-2)}
    
    0 讨论(0)
  • 2021-01-30 06:19

    Here's what I did for a script where I'm asking for a day, range of days, regex, etc. with a default to the improved regexes shared by paxdiablo.

    for day in $days
        do if [ 1 -eq "${#day}"] ; then
            day="0$day"
        fi
    

    I just run through this at the beginning of my loop where I run a bunch of log analysis on the day in question, buried in directories with leading zeroes.

    0 讨论(0)
  • 2021-01-30 06:20
    path=/tmp
    ruby -rfileutils -e '1.upto(31){|x| FileUtils.mkdir "'$path'/02.%02d.2011" % x}'
    
    0 讨论(0)
  • 2021-01-30 06:21

    In Bash 4, brace range expansions will give you leading zeros if you ask for them:

    for i in {01..31}
    

    without having to do anything else.

    If you're using earlier versions of Bash (or 4, for that matter) there's no need to use an external utility such as seq:

    for i in {1..31}
    

    or

    for ((i=1; i<=31; i++))
    

    with either of those:

    mkdir "$path/02.$(printf '%02d' "$i").2011"
    

    You can also do:

    z='0'
    mkdir "$path/02.${z: -${#i}}$i.2011"
    

    Using paxdiablo's suggestion, you can make all the directories at once without a loop:

    mkdir "$path"/02.{0{1..9},{10..31}}.2011
    
    0 讨论(0)
提交回复
热议问题