bash 在bash中通过向文件名添加数字来重命名文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17188501/
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
Renaming files with adding a number to filename in bash
提问by Stefan
I have lots of file like these:
我有很多这样的文件:
13831_1.jpg
13838_1.jpg
138035_1.jpg
138037_1.jpg
138039_1.jpg
I need to add a value of 5000000 to the numbers of the filenames. The result should be the following:
我需要将 5000000 的值添加到文件名的编号中。结果应如下所示:
5013831_1.jpg
5013838_1.jpg
5138035_1.jpg
5138037_1.jpg
5138039_1.jpg
Is there a way to do it with bash or perl?
有没有办法用 bash 或 perl 做到这一点?
回答by
Do: rename -v. If it will output:
做:rename -v。如果它会输出:
Usage: rename [-v] [-n] [-f] perlexpr [filenames]
This check is because there are at least two different rename tools, with very different functionalities. And the solution I'm having requires rename that handles perlexpr.
这种检查是因为至少有两个不同的重命名工具,具有非常不同的功能。我的解决方案需要重命名来处理 perlexpr。
Then you can:
然后你可以:
rename 's/^(\d+)/5000000+/e' *.jpg
回答by doubleDown
One way to do this using only bash
一种方法来做到这一点,只使用 bash
for file in *.jpg; do
number=${file%_*}
therest=${file#$number}
mv "$file" "$((number+5000000))$therest"
done
Notes:
笔记:
*.jpgwill expand to a list of.jpgfiles in current directory (ref: Filename expansion).${file%_*}removes everything after_in the file name and return it. (ref: Shell parameter expansion)${file#$number}removes the content of variablenumberfrom the beginning of the file name and return it. (ref: Shell parameter expansion)$((number+5000000))evaluates the arithmetic expression inside and returns the result (ref: Arithmetic expansion)
*.jpg将扩展到.jpg当前目录中的文件列表(参考:文件名扩展)。${file%_*}删除_文件名后面的所有内容并返回。(参考:Shell 参数扩展)${file#$number}number从文件名的开头删除变量的内容并返回它。(参考:Shell 参数扩展)$((number+5000000))计算里面的算术表达式并返回结果(参考:算术展开)
回答by ankit singh
$filename = "13831_1.jpg";
$org = explode("_".$filename);
$addnumber = 5000000+$org[0];
$string = implode("_",$addnumber);

