我需要循环一些值,
for i in $(seq $first $last)
do
does something here
done
对于$first和$last,我需要它的固定长度为5。所以如果输入是1,我需要在前面加上0,这样它就变成了00001。例如,它循环到99999,但长度必须是5。
例如:00002,00042,00212,12312等等。
你知道我该怎么做吗?
我需要循环一些值,
for i in $(seq $first $last)
do
does something here
done
对于$first和$last,我需要它的固定长度为5。所以如果输入是1,我需要在前面加上0,这样它就变成了00001。例如,它循环到99999,但长度必须是5。
例如:00002,00042,00212,12312等等。
你知道我该怎么做吗?
当前回答
你可以做得更简单
for i in {00001..99999}; do
echo $i
done
其他回答
这也会起作用:
for i in {0..9}{0..9}{0..9}{0..9}
do
echo "$i"
done
一种不使用外部进程分叉的方法是字符串操作,在一般情况下,它看起来像这样:
#start value
CNT=1
for [whatever iterative loop, seq, cat, find...];do
# number of 0s is at least the amount of decimals needed, simple concatenation
TEMP="000000$CNT"
# for example 6 digits zero padded, get the last 6 character of the string
echo ${TEMP:(-6)}
# increment, if the for loop doesn't provide the number directly
TEMP=$(( TEMP + 1 ))
done
这在WSL上也能很好地工作,在WSL中,分叉是一个非常繁重的操作。我有一个110000个文件列表,使用printf“%06d”$NUM花了1分钟多,上面的解决方案在1秒左右运行。
其他方式:
zeroos="000"
echo
for num in {99..105};do
echo ${zeroos:${#num}:${#zeroos}}${num}
done
转换任何数字的简单函数是:
function leading_zero(){
local num=$1
local zeroos=00000
echo ${zeroos:${#num}:${#zeroos}}${num}
}
如果序列的结尾有最大的填充长度(例如,如果你想要5个数字,命令是seq 1 10000),那么你可以为seq使用-w标志-它自己添加填充。
seq -w 1 10
会产生
01
02
03
04
05
06
07
08
09
10
像这样使用awk:
awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'
输出:
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
更新:
作为纯bash的替代方案,你可以这样做来获得相同的输出:
for i in {1..10}
do
printf "%05d\n" $i
done
通过这种方式,您可以避免使用外部程序seq,该程序在所有*nix版本中都不可用。