Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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[three-digits].txt

  • from filename001.txt
  • to.... filename440.txt.

I store the three digits as a number in a variable and increment the variable in a while loop. How can I increment the number without it losing its leading zeroes?

#!/bin/bash
clear

# [...] code for handling storage

episode=001
last=440

secnow_transcript_url="https://www.grc.com/sn/sn-"
last_token=".txt"

while [ $episode -le $last ]; do
    curl -X GET $secnow_transcript_url$episode$last_token > # storage location
    episode=$[$episode+001];
    sleep 60 # Don't stress the server too much!
done

I searched a lot and discovered nice approaches of others, that do solve my problem, but out of curiosity I would love to know if there is solution to my problem that keeps the while-loop, despite a for-loop would be more appropriate in the first place, as I know the range, but the day will come, when I will need a while loop! :-)

#!/bin/bash
for episode in $(seq -w 01 05); do
    curl -X GET $secnow_transcript_url$episode$last_token > # ...
done

or for just a few digits (becomes unpractical for more digits)

#!/bin/bash
for episode in 00{1..9} 0{10..99} {100..440}; do
    curl -X GET $secnow_transcript_url$episode$last_token > # ...
done
like image 663
Senkaku Avatar asked Dec 06 '25 17:12

Senkaku


2 Answers

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
like image 150
that other guy Avatar answered Dec 09 '25 14:12

that other guy


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
like image 26
glenn jackman Avatar answered Dec 09 '25 15:12

glenn jackman