How can I increment a number in a while-loop while preserving leading zeroes (BASH < V4)

后端 未结 3 2190
旧时难觅i
旧时难觅i 2020-12-19 22:56

I am trying to write a BASH script that downloads some transcripts of a podcast with cURL. All transcript files have a name that only differs by three digits: filename

相关标签:
3条回答
  • 2020-12-19 23:46

    You can use $((10#$n)) to remove zero padding (and do calculations), and printf to add zero padding back. Here are both put together to increment a zero padded number in a while loop:

    n="0000123"
    digits=${#n} # number of digits, here calculated from the original number
    while sleep 1
    do
        n=$(printf "%0${digits}d\n" "$((10#$n + 1))")
        echo "$n"
    done
    
    0 讨论(0)
  • 2020-12-19 23:47

    for ep in {001..440} should work.

    But, as you want a while loop: let printf handle leading zeroes

    while (( episode <= last )); do
        printf -v url "%s%03d%s" $secnow_transcript_url $episode $last_token
        curl -X GET $url > # storage location
        (( episode++ ))
        sleep 60 # Don't stress the server too much!
    done
    
    0 讨论(0)
  • 2020-12-19 23:53

    Will this do?

    #!/bin/bash
    
    i=1
    zi=000000000$i
    s=${zi:(-3)}
    echo $s
    
    0 讨论(0)
提交回复
热议问题