bash 通过添加数字批量重命名文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19468016/
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
bash to batch rename files with adding numbers
提问by qliq
I have a bunch of .jpg files with random names. I want a bash script to rename them like this:
我有一堆带有随机名称的 .jpg 文件。我想要一个 bash 脚本像这样重命名它们:
basename-0.jpg
basename-1.jpg
basename-2.jpg
.
.
.
.
basename-1000.jpg
I wrote this:
我是这样写的:
n = 0;
for file in *.jpg ; do mv "${file}" basename"${n}".jpg; n+=1; done
But the problem with the above bash is that in the loop, n is considered as string so n+1 just adds another '1' to the end of newly moved file. Appreciate your hints.
但上述 bash 的问题在于,在循环中,n 被视为字符串,因此 n+1 只是在新移动文件的末尾添加另一个“1”。欣赏你的提示。
回答by Yann Moisan
Use $((expression))
for arithmetic expansion in bash shell
使用$((expression))
在bash shell的算术扩展
n=0;
for file in *.jpg ; do mv "${file}" basename"${n}".jpg; n=$((n+1)); done
回答by John B
Bash
can also pre/post increment/decrement variable values using arithmetic evaluation syntax like ((var++))
.
Bash
还可以使用算术计算语法如((var++))
.
n=0;
for file in *.jpg ; do mv "${file}" basename"${n}".jpg; ((n++)); done
回答by AsymLabs
Did you want 'basename' or $(basename)? More generalized forms are:
你想要'basename'还是$(basename)?更一般的形式是:
# create basename-0.jpg, basename-1.jpg, ... basename-n.jpg
e='jpg'; j=0; for f in *.$e; do mv "$f" basename-$((j++)).$e; done
or
或者
# preserve stem: <stemA>-0.jpg, <stemB>-1.jpg, ... <stem?>-n.jpg
e='jpg'; j=0; for f in *.$e; do mv "$f" "${f%.*}"-$((j++)).$e; done