我需要循环一些值,
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等等。
你知道我该怎么做吗?
当前回答
使用printf非常简单
[jaypal:~/Temp] printf "%05d\n" 1
00001
[jaypal:~/Temp] printf "%05d\n" 2
00002
其他回答
一种不使用外部进程分叉的方法是字符串操作,在一般情况下,它看起来像这样:
#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秒左右运行。
如果你想要N个数字,加10^N并删除第一个数字。
for (( num=100; num<=105; num++ ))
do
echo ${num:1:3}
done
输出:
01
02
03
04
05
使用printf非常简单
[jaypal:~/Temp] printf "%05d\n" 1
00001
[jaypal:~/Temp] printf "%05d\n" 2
00002
如果你只是想用0填充数字以达到固定长度,只需添加最接近10的倍数 如。对于2位数字,加10^2,然后在显示输出之前删除第一个1。
此解决方案适用于填充/格式化任意长度的单个数字,或使用for循环填充/格式化整个数字序列。
# Padding 0s zeros:
# Pure bash without externals eg. awk, sed, seq, head, tail etc.
# works with echo, no need for printf
pad=100000 ;# 5 digit fixed
for i in {0..99999}; do ((j=pad+i))
echo ${j#?}
done
在Mac OSX 10.6.8, Bash ver 3.2.48上测试
使用printf和“%05d”,例如:
printf "%05d" 1