如何零垫整数序列在bash,使所有具有相同的宽度? [英] How to zero pad a sequence of integers in bash so that all have the same width?
问题描述
我需要循环一些值,
for i in $(seq $first $last)
do
does something here
done
有关 $第一个
和 $最后
,我需要它是固定长度5.因此,如果输入为 1
,我需要添加零在前面,使得它成为 00001
。它会循环到 99999
为例,但长度必须是5。
For $first
and $last
, i need it to be of fixed length 5. So if the input is 1
, i need to add zeros in front such that it becomes 00001
. It loops till 99999
for example, but the length has to be 5.
例如: 00002
, 00042
, 00212
, 012312
等等。
我如何能做到这一点任何想法?
Any idea on how i can do that?
推荐答案
在特定的情况下,虽然它可能是最容易使用的 -f
标志 SEQ
来获得,因为它输出列表它格式化数字。例如:
In your specific case though it's probably easiest to use the -f
flag to seq
to get it to format the numbers as it outputs the list. For example:
for i in $(seq -f "%05g" 10 15)
do
echo $i
done
将产生以下的输出:
will produce the following output:
00010
00011
00012
00013
00014
00015
更一般地,庆典
的的printf
作为一个内置的,所以你可以用零垫输出如下:
More generally, bash
has printf
as a built-in so you can pad output with zeroes as follows:
$ i=99
$ printf "%05d\n" $i
00099
您可以使用 -v
标志存储在另一个变量输出:
You can use the -v
flag to store the output in another variable:
$ i=99
$ printf -v j "%05d" $i
$ echo $j
00099
注意的printf
支持一个稍微不同的格式,以 SEQ
,所以你需要使用 %05D
而不是%05克
。
Notice that printf
supports a slightly different format to seq
so you need to use %05d
instead of %05g
.
这篇关于如何零垫整数序列在bash,使所有具有相同的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!