Perl 的重命名 - 如何附加计数器?
Perl 安装时附带了一个不错的重命名实用程序。如何在 Perl 正则表达式中附加一个计数器?这是一个相关问题,例如当前目录中文件编号的问题:
rename 's/^/<here I'd like to have a number of a file being processed>/g' *
例如,如何将:重命名
fileA
fileB
fileC
为
1 - fileA
2 - fileB
3 - fileC
编辑:
我添加了计数器功能($c
变量) - 请参阅此处。它工作正常 - 但是当我尝试指定计数器格式时:
rename_c.pl -c 5.2f 's/^/$c - /' *
它说:
Useless use of concatenation (.) or string in void context at line 120.
并且它并没有真正使用我告诉它使用的格式。这一定是第 120 行中的一些简单语法错误。您能看一下吗?
There's a nice renaming utility, which comes with Perl's installation. How one would append a counter in the Perl regexp? This is a relevant question e.g. for a problem of numbering files in the current directory:
rename 's/^/<here I'd like to have a number of a file being processed>/g' *
For example how would one rename:
fileA
fileB
fileC
to
1 - fileA
2 - fileB
3 - fileC
Edit:
I've added the counter feature ($c
variable) - see here. It works fine - but when I try to specify the counter format:
rename_c.pl -c 5.2f 's/^/$c - /' *
it says:
Useless use of concatenation (.) or string in void context at line 120.
and it doesn't really use the format I told it to use. This must be some simple syntax mistake in a line number 120. Can You please take a look?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
基本的重命名实用程序可以很好地处理这种情况:
The basic rename utility can handle that situation just fine:
有问题的代码行是:
您不希望有
eval
;您可以简单地将格式创建为字符串:字符串(第一个参数)最终包含所请求的格式,并且
sprintf()
使用该格式格式化$cNumber
。The line of code in question is:
You don't want the
eval
there; you can simply create the format as a string:The string (first argument) ends up containing the format requested, and
sprintf()
formats$cNumber
using that.如果您在 macOS 上并使用通过
brew install rename
安装的工具,则以下内容应该有效:示例:
If you are on macOS and using tool installed via
brew install rename
, then following should work:Example:
perl one-liner 如果您有权访问 perl 本身
对
txt
文件列表进行试运行重命名
perl -le
运行一行代码($old=$_)
保存旧名称/^/
匹配乞求++$n
从 1 开始计数器/eg
全局运行,e
用于评估rename($old,$_)
重命名$old
=>;$_
for <*.txt>
循环遍历txt
文件列表您可以使用此模式重命名所有内容对于高级重命名,您可能还需要使用 sprintf。
屏幕截图
perl one-liner if you have access to perl itself
dry run over list of
txt
filesrename
perl -le
run a one-liner($old=$_)
save the old name/^/
match the begging++$n
start a counter from 1/eg
run globally ande
is for evaluationrename($old,$_)
rename the$old
=>$_
for <*.txt>
loop over list oftxt
fileYou can rename everything with this pattern and for advanced renaming you may want to use
sprintf
as well.screenshot