从命令行重命名多个文件 [英] Rename multiple files from command line
问题描述
可能重复:
根据模式重命名Linux中的许多文件
Possible Duplicate:
Renaming lots of files in Linux according to a pattern
我有多个这种格式的文件:
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
我知道您可以使用'rename'重命名多个文件,但是在这种情况下我不知道该怎么做.
I know you can rename multiple files with 'rename', but I don't know how to do this in this case.
推荐答案
您可以使用Perl工具shell提示符下输入> rename
. (有其他同名工具可能无法执行此操作,因此请小心.)
You can do this using the Perl tool rename
from the shell
prompt. (There are other tools with the same name which may or may not be able to do this, so be careful.)
rename 's/(\d+)/sprintf("%03d", $1)/e' *.pdf
如果要进行试运行以确保不破坏任何文件,请在命令中添加-n
开关.
If you want to do a dry run to make sure you don't clobber any files, add the -n
switch to the command.
如果运行以下命令(linux
)
$ file $(readlink -f $(type -p rename))
,结果为
.../rename: Perl script, ASCII text executable
那么这似乎是正确的工具=)
then this seems to be the right tool =)
这似乎是Ubuntu
上的默认rename
命令.
This seems to be the default rename
command on Ubuntu
.
将其设置为Debian
上的默认值以及诸如Ubuntu
的派生类:
To make it the default on Debian
and derivative like Ubuntu
:
sudo update-alternatives --set rename /path/to/rename
说明
-
s///
是基本替换表达式:s/to_replace/replaced/
,检查perldoc perlre
-
(\d+)
用()
捕获至少一个整数:$1
中的\d
或更大的+
-
sprintf("%03d", $1)
sprintf
类似于printf
,但不用于打印,而是用于格式化具有相同语法的字符串.%03d
用于零填充,$1
是捕获的字符串.检查perldoc -f sprintf
- 允许更高版本的 perl函数,因为表达式 末尾的
s///
is the base substitution expression :s/to_replace/replaced/
, checkperldoc perlre
(\d+)
capture with()
at least one integer :\d
or more :+
in$1
sprintf("%03d", $1)
sprintf
is likeprintf
, but not used to print but to format a string with the same syntax.%03d
is for zero padding, and$1
is the captured string. Checkperldoc -f sprintf
- the later perl's function is permited because of the
e
modifier at the end of the expression
e
修饰符
Explanations
这篇关于从命令行重命名多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!