bash 如何将 printf 语句的结果分配给变量(用于前导零)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18948594/
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
How to assign results from printf statement to a variable (for leading zeroes)?
提问by Tom S?derlund
I'm writing a shell script (Bash on Mac OS X) to rename a bunch of image files. I want the results to be:
我正在编写一个 shell 脚本(Mac OS X 上的 Bash)来重命名一堆图像文件。我希望结果是:
frame_001
frame_002
frame_003
etc.
等等。
Here is my code:
这是我的代码:
let framenr=$[1 + (y * cols * resolutions) + (x * resolutions) + res]
echo $framenr:
let framename=$(printf 'frame_%03d' $framenr)
echo $framename
$framenr
looks correct, but $framename
always becomes 0
. Why?
$framenr
看起来正确,但$framename
总是变成0
. 为什么?
回答by glenn Hymanman
The let
command forces arithmetic evaluation, and the referenced "variable" does not exist, so you get the default value 0.
该let
命令强制算术评估,并且引用的“变量”不存在,因此您获得默认值 0。
y=5
x=y; echo $x # prints: y
let x=y; echo $x # prints: 5
Do this instead:
改为这样做:
framenr=$(( 1 + (y * cols * resolutions) + (x * resolutions) + res ))
echo $framenr:
# if your bash version is recent enough
printf -v framename 'frame_%03d' $framenr
# otherwise
framename=$(printf 'frame_%03d' $framenr)
echo $framename
I recall reading somewhere that $[ ]
is deprecated. Use $(( ))
instead.
我记得在某个$[ ]
已弃用的地方阅读过。使用$(( ))
来代替。