如何在保留前导零的同时在 while 循环中增加数字(BASH < V4) [英] How can I increment a number in a while-loop while preserving leading zeroes (BASH < V4)

查看:13
本文介绍了如何在保留前导零的同时在 while 循环中增加数字(BASH < V4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 BASH 脚本,用于下载带有 cURL 的播客的一些成绩单.所有转录文件的名称仅相差三位数:filename[three-digits].txt

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

  • 来自 filename001.txt
  • 到.... filename440.txt.

我将三个数字作为数字存储在变量中,并在 while 循环中递增变量.如何在不丢失前导零的情况下增加数字?

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

<小时>

我搜索了很多,发现了其他人的好方法,确实如此解决我的问题,但出于好奇,我很想知道是否有解决我的问题的方法可以保持 while 循环,尽管首先使用 for 循环会更合适,因为我知道范围,但总有一天,我需要一个 while 循环!:-)


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

推荐答案

您可以使用 $((10#$n)) 去除零填充(并进行计算),以及 printf 添加零填充.这里将两者放在一起以在 while 循环中增加一个零填充的数字:

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
" "$((10#$n + 1))")
    echo "$n"
done

这篇关于如何在保留前导零的同时在 while 循环中增加数字(BASH &lt; V4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆