本文介绍了如何在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.
  • from filename001.txt
  • to.... 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


我搜索了很多内容,并且发现了其他方法,解决了我的问题,但出于好奇,我很想知道是否有解决我的问题的方法,而知道范围,但是这一天将会到来,那时候我需要一会儿循环! :-)


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

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

10-29 16:50