bash 从命令行重命名多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14327613/
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
Rename multiple files from command line
提问by Simon Dirmeier
Possible Duplicate:
Renaming lots of files in Linux according to a pattern
可能的重复:
根据模式重命名 Linux 中的大量文件
I have multiple files in this format:
我有多个这种格式的文件:
file_1.pdf
file_2.pdf
...
file_100.pdf
My question is how can I rename all files, that look like this:
我的问题是如何重命名所有文件,如下所示:
file_001.pdf
file_002.pdf
...
file_100.pdf
I know you can rename multiple files with 'rename', but I don't know how to do this in this case.
我知道您可以使用“重命名”重命名多个文件,但在这种情况下我不知道如何执行此操作。
回答by Gilles Quenot
You can do this using the Perl tool renamefrom the shellprompt. (There are other tools with the same name which may or may not be able to do this, so be careful.)
您可以rename在shell提示符下使用 Perl 工具执行此操作。(还有其他同名的工具可能会也可能不会这样做,所以要小心。)
rename 's/(\d+)/sprintf("%03d", )/e' *.pdf
If you want to do a dry run to make sure you don't clobber any files, add the -nswitch to the command.
如果要进行试运行以确保不会破坏任何文件,请将-n开关添加到命令中。
note
笔记
If you run the following command (linux)
如果您运行以下命令 ( linux)
$ file $(readlink -f $(type -p rename))
and you have a result like
你有这样的结果
.../rename: Perl script, ASCII text executable
then this seems to be the right tool =)
那么这似乎是正确的工具 =)
This seems to be the default renamecommand on Ubuntu.
这似乎是默认rename的命令Ubuntu。
To make it the default on Debianand derivative like Ubuntu:
要使其成为默认值Debian和衍生物,例如Ubuntu:
sudo update-alternatives --set rename /path/to/rename
Explanations
说明
s///is the base substitution expression :s/to_replace/replaced/, checkperldoc perlre(\d+)capture with()at least one integer :\dor more :+in$1sprintf("%03d", $1)sprintfis likeprintf, but not used to printbut to formata string with the same syntax.%03dis for zero padding, and$1is the captured string. Checkperldoc -f sprintf- the later perl's functionis permited because of the
emodifier at the end of the expression
s///是基本替换表达式:s/to_replace/replaced/,检查perldoc perlre(\d+)使用()至少一个整数捕获:\d或多个:+在$1sprintf("%03d", $1)sprintf类似于printf,但不用于打印,而是用于格式化具有相同语法的字符串。%03d用于零填充,并且$1是捕获的字符串。查看perldoc -f sprintf- 由于表达式末尾的修饰符,允许使用后面的perl 函数
e
回答by Gilbert
If you want to do it with pure bash:
如果你想用纯 bash 来做:
for f in file_*.pdf; do x="${f##*_}"; echo mv "$f" "${f%_*}$(printf '_%03d.pdf' "${x%.pdf}")"; done
(note the debugging echo)
(注意调试echo)

