Senkaku
Senkaku

Reputation: 197

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

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

Upvotes: 3

Views: 2419

Answers (3)

Geordee Naliyath
Geordee Naliyath

Reputation: 1859

Will this do?

#!/bin/bash

i=1
zi=000000000$i
s=${zi:(-3)}
echo $s

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246867

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

Upvotes: 1

that other guy
that other guy

Reputation: 123490

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

Upvotes: 6

Related Questions