确保int变量长度为2位,否则在前面添加0使其长度为2位
如何检查 int 变量 ($inputNo) 以查看其长度是否为 2 位或更多十进制数字?
示例:
inputNo="5"
应该更改为: 05
inputNo="102"
应该保留: 102
我考虑过使用 wc
和 if
语句,但是 wc -m
没有t 似乎给出了传递到 wc
的实际字符,因为 wc
似乎总是给给定的字符+1。
但我不知道如何在当前输入的数字前面添加0。
How do I check a int variable ($inputNo) to see if it’s 2 or more decimal digits long?
Example:
inputNo="5"
Should be changed to: 05
inputNo="102"
Should be left alone: 102
I thought about using wc
and if
statements, but wc -m
doesn’t seems to give the actual characters passed into wc
, as wc
always seems to give +1 to the characters that is given.
But I don’t know how to add a 0 in front of the current input number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 bash 内置的
printf
和-v
选项将其写入变量,而不是将其打印到标准输出:您需要确保它是数字首先,否则转换将失败。如果您希望能够将任何字符串填充为两个或更多字符,您还可以使用:
这基本上是一个
while
循环,在字符串前面加上“0”前缀直到长度大于或等于2。请注意,这也可以在 bash 中完成,方法是在数字前加上两个零,然后简单地获取该字符串的最后两个字符,首先检查它是否至少还没有达到所需的大小:
区别可能是对于两位数来说不是太大,但如果您需要更大的宽度,您可能会发现后一种解决方案更好。
如果您使用的 shell 不是
bash
(不太可能,根据您的标签),您需要找到等效项,或者恢复使用外部进程来执行工作,类似于:这基本上完成了您在问题中的想法,但请注意在
echo
命令中使用-n
来防止尾随换行符(这是几乎肯定会导致您的差一错误)。但是,如前所述,这是一个后备位置。如果您使用的是
bash
,我之前的建议可能是最好的。You can use the bash-builtin
printf
with the-v
option to write it to a variable rather than print it to standard output:You'll want to make sure it's numeric first otherwise the conversion will fail. If you want to be able to pad any string out to two or more characters, you can also use:
which is basically a
while
loop that prefixes your string with "0" until the length is greater than or equal to two.Note that this can also be done in
bash
by prefixing the number with two zeroes then simply getting the last two characters of that string, checking first that it's not already at least the desired size:The difference is probably not too great for a two-digit number but you may find the latter solution is better if you need larger widths.
If you're using a shell other than
bash
(unlikely, based on your tags), you'll need to find the equivalents, or revert to using external processes to do the work, something like:This does basically what you were thinking off in your question but note the use of
-n
in theecho
command to prevent the trailing newline (which was almost certainly causing your off-by-one error).But, as stated, this is a fall-back position. If you're using
bash
, the earlier suggestions of mine are probably best.用于通用填充,无论字符串是否为数字
无需将
echo
管道传输到wc
或使用while
> 循环。在 Bash 中,您可以像这样获取字符串的长度:
${#inputNo}
。既然你可以做子字符串,你可以这样做:
For general-purpose padding whether the string is numeric or not
No need for piping
echo
intowc
or using awhile
loop.In Bash, you can get the length of a string like this:
${#inputNo}
.And since you can do substrings, you can do this instead:
您可以使用 http://bash-hackers.org/wiki/doku .php/commands/builtin/printf,其中的示例:
You can use http://bash-hackers.org/wiki/doku.php/commands/builtin/printf, an example from there: