Perl's rename - how to append a counter?

偶尔善良 提交于 2020-01-03 02:33:06

问题


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?


回答1:


The line of code in question is:

$c = sprintf(eval("%" . "$form", $cNumber));

You don't want the eval there; you can simply create the format as a string:

$c = sprintf("%$form", $cNumber));

The string (first argument) ends up containing the format requested, and sprintf() formats $cNumber using that.




回答2:


The basic rename utility can handle that situation just fine:

$ rename '$_ = sprintf "%d - %s", ++$count, $_' files...


来源:https://stackoverflow.com/questions/8257032/perls-rename-how-to-append-a-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!