Perl's rename - how to append a counter?

2019-06-07 03:48发布

问题:

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...