bash 在字符串中填充零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1117134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Padding zeros in a string
提问by ChristopheD
I'm writing a bash script to get some podcasts. The problem is that some of the podcast numbers are one digits while others are two/three digits, therefore I need to pad them to make them all 3 digits.
我正在编写一个 bash 脚本来获取一些播客。问题是一些播客编号是一位数字,而其他播客编号是两位/三位数字,因此我需要填充它们以使其全部为 3 位数字。
I tried the following:
我尝试了以下方法:
n=1
n = printf %03d $n
wget http://aolradio.podcast.aol.com/sn/SN-$n.mp3
but the variable 'n' doesn't stay padded permanently. How can I make it permanent?
但变量“n”不会永久填充。我怎样才能让它永久?
回答by ChristopheD
Use backticks to assign the result of the printf command (``):
使用反引号分配 printf 命令的结果 (``):
n=1
wget http://aolradio.podcast.aol.com/sn/SN-`printf %03d $n`.mp3
EDIT: Note that i removed one line which was not really necessary. If you want to assign the output of 'printf %...' to n, you could use
编辑:请注意,我删除了一行并不是真正必要的。如果要将 'printf %...' 的输出分配给 n,可以使用
n=`printf %03d $n`
and after that, use the $n variable substitution you used before.
之后,使用您之前使用的 $n 变量替换。
回答by nos
Seems you're assigning the return value of the printf command (which is its exit code), you want to assign the output of printf.
似乎您正在分配 printf 命令的返回值(这是它的退出代码),您想分配 printf 的输出。
bash-3.2$ n=1
bash-3.2$ n=$(printf %03d $n)
bash-3.2$ echo $n
001
回答by UnSandpiper
Attention though if your input string has a leading zero!
printf will still do the padding, but also convert your string to hexoctal format.
请注意,如果您的输入字符串有前导零!
printf 仍然会进行填充,但也会将您的字符串转换为十六进制八进制格式。
# looks ok
$ echo `printf "%05d" 03`
00003
# but not for numbers over 8
$ echo `printf "%05d" 033`
00027
A solution to this seems to be printing a float instead of decimal.
The trick is omitting the decimal places with .0f
.
对此的解决方案似乎是打印浮点数而不是小数点。
诀窍是省略小数位.0f
。
# works with leading zero
$ echo `printf "%05.0f" 033`
00033
# as well as without
$ echo `printf "%05.0f" 33`
00033
回答by cC Xx
to avoid context switching:
避免上下文切换:
a="123"
b="00000${a}"
c="${b: -5}"
回答by cC Xx
n=`printf '%03d' "2"`
Note spacing and backticks
注意间距和反引号
回答by Rob Wells
As mentioned by noselad, please command substitution, i.e. $(...), is preferable as it supercedes backtics, i.e. `...`
.
正如noselad 所提到的,请命令替换,即$(...),因为它取代了backtics,即`...`
。
Much easier to work with when trying to nest several command substitutions instead of escaping, i.e. "backslashing", backtics.
尝试嵌套多个命令替换而不是转义时更容易使用,即“反斜杠”,backtics。