但使用printf在bash脚本离奇的问题:" 09"和" 08"是无效的数字," 07"和" 06"很好 [英] Bizarre issue with printf in bash script:"09" and "08" are invalid numbers, "07" and "06" are fine

查看:289
本文介绍了但使用printf在bash脚本离奇的问题:" 09"和" 08"是无效的数字," 07"和" 06"很好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的bash脚本 - 我只是想离开垫用零一组数字:

This is my bash script - I just want to left-pad a set of numbers with zeroes:

printf "%04d" "09"
printf "%04d" "08"
printf "%04d" "07"
printf "%04d" "06"

输出:

./rename.sh: line 3: printf: 09: invalid number 
0000
./rename.sh: line 4: printf: 08: invalid number 
0000 
0007
0006

......怎么办?

What...?

09只和08是导致该问题:在我的顺序每隔数似乎是确定。

Only 09 and 08 are causing the problem: every other number in my sequence seems to be OK.

推荐答案

如果你有你的09在一个变量,你可以做

If you have your "09" in a variable, you can do

a="09"
echo "$a"
echo "${a#0}"
printf "%04d" "${a#0}"

为什么此帮助?好了,一些字面出发与 0 但有没有 X 在第2位是国际preTED为八进制值。

Why does this help? Well, a number literal starting with 0 but having no x at the 2nd place is interpreted as octal value.

八进制值只有数字 0 .. 7 8 9 是未知的。

Octal value only have the digits 0..7, 8 and 9 are unknown.

$ {A#0}去掉一条通往 0 。结果值可给的printf 然后,它适当地打印了,以 0 prefixed,在4数字。

"${a#0}" strips one leading 0. The resulting value can be fed to printf then, which prints it appropriately, with 0 prefixed, in 4 digits.

如果您有期待,你得到的值,如009,事情就因为你将不得不使用一个循环,消除所有多余的<更为复杂code> 0 ,或在评论中提及的 extglob 前pression。

If you have to expect that you get values such as "009", things get more complicated as you'll have to use a loop which eliminates all excess 0s at the start, or an extglob expression as mentioned in the comments.

这篇关于但使用printf在bash脚本离奇的问题:&QUOT; 09&QUOT;和&QUOT; 08&QUOT;是无效的数字,&QUOT; 07&QUOT;和&QUOT; 06&QUOT;很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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