bash中的printf:"09";和"08"表示是无效数字,"07"表示无效和"06"很好 [英] printf in bash: "09" and "08" are invalid numbers, "07" and "06" are fine
问题描述
这是我的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
什么...?
仅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
的数字文字被解释为八进制值.
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
,然后以4位为前缀,适当地打印出带有0
的值.
"${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"
之类的值,事情将变得更加复杂,因为您必须使用一个循环来消除开始时所有多余的0
,或者使用extglob
表达式作为在评论中提到.
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 0
s at the start, or an extglob
expression as mentioned in the comments.
这篇关于bash中的printf:"09";和"08"表示是无效数字,"07"表示无效和"06"很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!