如何在 Bash 中增加零填充的 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5584470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment a zero padded int in Bash
提问by Juan
I have a set of records to loop. The numbers range from 0000001 to 0089543 that ill call UIDX.
我有一组要循环的记录。编号范围从 0000001 到 0089543 的错误呼叫 UIDX。
if i try something like:
如果我尝试类似的事情:
for ((i=0; i< 0089543; i++)); do
((UIDX++))
done
counter increments 1, 2, 3, 4 as opposed to the 0000001, 0000002... that i need.
计数器递增 1、2、3、4,而不是我需要的 0000001、0000002...。
what is the best way to pad those leading zero's?
填充那些前导零的最佳方法是什么?
回答by Sean
Use the printfcommand to format the numbers with leading zeroes, eg:
使用printf命令用前导零格式化数字,例如:
for ((i = 0; i < 99; ++i)); do printf -v num '%07d' $i; echo $num; done
From man bash:
来自man bash:
printf [-v var] format [arguments]
Write the formatted arguments to the standard output under the control of the format. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output.
printf [-v var] format [arguments]
在格式的控制下将格式化的参数写入标准输出。-v 选项导致将输出分配给变量 var 而不是打印到标准输出。
回答by pfnuesel
Bash 4 has a nice way to solve this:
Bash 4 有一个很好的方法来解决这个问题:
for i in {0000000..0089543}; do
echo $i
done
回答by Alberto Zaccagni
You could use the seq command, very useful in your situation
您可以使用 seq 命令,在您的情况下非常有用
seq -w 0089543
Remove the first and last number according to your need, for example, if you need to arrive to 0089542 then the command to use is
根据你的需要去掉第一个和最后一个数字,例如,如果你需要到达 0089542 那么使用的命令是
seq -w 0089542

