I want a script can do this

J

Jacky Cheung

[Note: parts of this message were removed to make it a legal post.]

I want a script can do this:
a directory aa , under aa has many files. i want batch rename all files.
like this
the file name is test01 test02 test03 ... test09 test10 test11... test29....
rename
test1 test2 test3 ....test9 test10 test29.....

how can i write this script?
 
B

brabuhr

I want a script can do this:
a directory aa , under aa has many files. i want batch rename all files.
like this
the file name is test01 test02 test03 ... test09 test10 test11... test29....
rename
test1 test2 test3 ....test9 test10 test29.....

how can i write this script?

One possible method to map the file names:

irb(main):001:0> a = %w{ test01 test02 test03 test09 test10 test11 }
=> ["test01", "test02", "test03", "test09", "test10", "test11"]
irb(main):002:0> b = a.map{|i| i.scan(/([^\d]+)(\d+)/).flatten }
=> [["test", "01"], ["test", "02"], ["test", "03"], ["test", "09"],
["test", "10"], ["test", "11"]]
irb(main):003:0> c = b.map{|i| [ i[0], i[1].to_i ].join }
=> ["test1", "test2", "test3", "test9", "test10", "test11"]
 
R

Ryan Davis

I want a script can do this:
a directory aa , under aa has many files. i want batch rename all
files.
like this
the file name is test01 test02 test03 ... test09 test10 test11...
test29....
rename
test1 test2 test3 ....test9 test10 test29.....

how can i write this script?

Below is an equivalent perl script that I've used for years and years.
It should be exceedingly simple to convert to ruby (or just use it as-
is) and/or simplify for your requirements.

You'd use it like so:
% rename 's/(\D)0+(\d)/$1$2/' aa/*


Here ya go:
#!/usr/bin/perl -w

# Usage: rename perlexpr [files]

($op = shift) || die "Usage: rename perlexpr [filenames]\n";
if (!@ARGV) {
@ARGV = <STDIN>;
chop(@ARGV);
}
for (@ARGV) {
$was = $_;
eval $op;
die $@ if $@;
rename($was,$_) unless $was eq $_;
}
 
H

Heesob Park

Hi,

2009/8/8 Jacky Cheung said:
I want a script can do this:
a directory aa , under aa has many files. i want batch rename all files.
like this
the file name is test01 test02 test03 ... test09 test10 test11... test29....
rename
test1 test2 test3 ....test9 test10 test29.....

how can i write this script?
Try this:
Dir.glob("aa/*").each{|f|File.rename(f,f.gsub(/test0+(?=\d)/,"test"))}

Regards,

Park Heesob
 

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

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,462
Latest member
ChanaLipsc

Latest Threads

Top