如何在shell中为for循环添加前导零? [英] How to add leading zeros for for-loop in shell?

查看:36
本文介绍了如何在shell中为for循环添加前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本数字 for 循环,它在每次迭代中将变量 num 增加 1...

I have a basic number for loop which increments the variable num by 1 over each iteration...

for (( num=1; num<=5; num++ ))
do
 echo $num
done

输出:

1
2
3
4
5

我试图让它产生输出(在 $num 之前添加前导零):

I'm trying to make it produce the output (add leading zero before $num):

01
02
03
04
05

不做:

echo 0$num

推荐答案

使用以下语法:

$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05

免责声明:前导零仅适用于 >=bash-4.

Disclaimer: Leading zeros only work in >=bash-4.

如果您想使用 printf,没有什么可以阻止您将其结果放入变量中以供进一步使用:

If you want to use printf, nothing prevents you from putting its result in a variable for further use:

$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05

这篇关于如何在shell中为for循环添加前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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