Increment Numbers

C

Chris Ellison

Hi,


"Larry's filename fixer"

------filename: rename-------------
#!/usr/bin/perl -w
# rename - Larry's filename fixer
$op = shift or die "Usage: rename expr [files]\n";
chomp(@ARGV = <STDIN>) unless @ARGV;
for (@ARGV) {
$was = $_;
eval $op;
die $@ if $@;
rename($was,$_) unless $was eq $_;
}
----------------------------------

I have a bunch of files 001.txt, 002.txt, 055.txt, 099.txt,... and
would like to increment them using the above script.

So, I was thinking something like this:

rename 's/(\d{3})/something/' *

Though, I don't know how to accomplish the "something".
I was thinking that it could be done with backreferencing:

$1+increment

but I don't know how to do operations within a regular expression.

Any suggestions?
 
X

Xicheng Jia

you may use sprintf() and regex's 'e' modifier:

rename 's/^(\d{3})/sprintf("%03d",$1+1)/e' *.txt

Xicheng
 
T

Tad McClellan

Xicheng Jia said:
you may use sprintf() and regex's 'e' modifier:


There is no such thing as an 'e' modifier for a regex.

rename 's/^(\d{3})/sprintf("%03d",$1+1)/e' *.txt


Oh. You meant the _substitution operator's_ 'e' modifier.



[snip TOFU]
 
T

Tad McClellan

Chris Ellison said:
rename 's/(\d{3})/something/' *

but I don't know how to do operations within a regular expression.


That's OK because you don't want to do an operation within
a regular expression, you want to do an operation within
the REPLACEMENT part of the s/// operator (which is (by default)
a string, not a regex).

Any suggestions?


Read the entry for s/// in perlop.pod, until you get to this part:

e Evaluate the right side as an expression.
 
D

Dave Weaver

<TOFU fixed>

you may use sprintf() and regex's 'e' modifier:

rename 's/^(\d{3})/sprintf("%03d",$1+1)/e' *.txt

But note that this will probably fail, depending on the order the
files are processed in.

If you start with 001.txt, and 002.txt, and it first renames 001.txt
to 002.txt, and then renames 002.txt to 003.txt, you'll find you've
lost a file and 003.txt is what was originally 001.txt.

You may be better off writing a small custom script to do the renaming
correctly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,177
Messages
2,570,954
Members
47,507
Latest member
codeguru31

Latest Threads

Top