| ↑↑↑ Home | ↑↑ UNIX | ↑ Updateware |
Perlers will know rename, the automatic file renamer originally written by Larry Wall, which comes with the Perl interpreter. Though very powerful, it cannot rename files as successive numbers, which is something one often wants. This cannot be fixed by a crafty Perl expression, either, since the expression is within the scope of one cycle of the loop.
For that reason I added an index variable $i to rename which is incremented for each processed file. By using that variable in the Perl expression, one can enumerate files or more generally rename them based on their position on the command line (or stdin). Because it is most practical in the most frequent case of enumerating files, the index variable starts at 1 and is padded with leading zeros to have the same width as the maximum index. When the index is used in arithmetic, Perl discards the leading zeros.
Get the modified rename: Download
Make it executable, put it somewhere in your path, extract the manual page (also updated) with pod2man or pod2html, and enjoy!
rename - renames multiple files
rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]
rename
renames the filenames supplied according to the rule specified as the
first argument.
The perlexpr
argument is a Perl expression which is expected to modify the $_
string in Perl for at least some of the filenames specified.
If a given filename is not modified by the expression, it will not be
renamed.
If no filenames are given on the command line, filenames will be read
via standard input, one per line.
For example, to rename all files matching *.bak to strip the extension,
you might say
rename 's/\.bak$//' *.bak
To translate uppercase names to lower, you'd use
rename 'y/A-Z/a-z/' *
The index of the file to be renamed is made available in the 1-based $i
variable, so you can enumerate files in chronological order like this:
ls -rt1 | rename 's/^/${i}_/'
Verbose: print names of files successfully renamed.
No Action: show what files would have been renamed.
Force: overwrite existing files.
Larry Wall; improvements by Robin Barker and Volker Schatz
mv(1), perl(1)
If you give an invalid Perl expression you'll get a syntax error.