如何在 bash 中对整数序列进行零填充,以便所有整数都具有相同的宽度? [英] How to zero pad a sequence of integers in bash so that all have the same width?

查看:23
本文介绍了如何在 bash 中对整数序列进行零填充,以便所有整数都具有相同的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要循环一些值,

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

对于$first$last,我需要它是固定长度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.

例如:000020004200212012312等等.

知道如何做到这一点吗?

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

将产生以下输出:

00010
00011
00012
00013
00014
00015

更一般地,bash 内置了 printf,因此您可以用零填充输出,如下所示:

More generally, bash has printf as a built-in so you can pad output with zeroes as follows:

$ i=99
$ printf "%05d
" $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 而不是 %05g.

Notice that printf supports a slightly different format to seq so you need to use %05d instead of %05g.

这篇关于如何在 bash 中对整数序列进行零填充,以便所有整数都具有相同的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆