我需要循环一些值,

for i in $(seq $first $last)
do
    does something here
done

对于$first和$last,我需要它的固定长度为5。所以如果输入是1,我需要在前面加上0,这样它就变成了00001。例如,它循环到99999,但长度必须是5。

例如:00002,00042,00212,12312等等。

你知道我该怎么做吗?


当前回答

1)。创建从1到1000的数字序列“seq”,并固定宽度“-w”(宽度由结束数字的长度决定,在本例中为1000的4位数字)。

2)。另外,使用'sed -n'选择您想要的数字(在本例中,我们选择数字1-100)。

3)。'echo'输出每个数字。数字存储在变量“i”中,使用“$”访问。

优点:这段代码非常干净。

缺点:'seq'不是所有Linux系统的本机(据我所知)

for i in `seq -w 1 1000 | sed -n '1,100p'`; 
do 
    echo $i; 
done

其他回答

使用printf非常简单

[jaypal:~/Temp] printf "%05d\n" 1
00001
[jaypal:~/Temp] printf "%05d\n" 2
00002

这也会起作用:

for i in {0..9}{0..9}{0..9}{0..9}
do
  echo "$i"
done

使用printf和“%05d”,例如:

printf "%05d" 1

一种不使用外部进程分叉的方法是字符串操作,在一般情况下,它看起来像这样:

#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秒左右运行。

在您的特定情况下,使用-f标志使seq在输出列表时格式化数字可能是最简单的。例如:

for i in $(seq -f "%05g" 10 15)
do
  echo $i
done

将产生以下输出:

00010
00011
00012
00013
00014
00015

更一般地说,bash内置了printf,所以你可以像下面这样用0填充输出:

$ i=99
$ printf "%05d\n" $i
00099

你可以使用-v标志将输出存储在另一个变量中:

$ i=99
$ printf -v j "%05d" $i
$ echo $j
00099

请注意,printf支持与seq略有不同的格式,因此您需要使用%05d而不是%05g。