UNIX Gurus please help: rename script

loekjehe

Registered
I have an output of a set of files named in alphabetic style, like filename.0aa, filename.0ab....filename0.zz and I want to rename these files into numeric style, like filename.001, filename.002 etc. This should be possible with a simple shell script. But I don't succeed. UNIX gurus please help! Thanks a lot.

Loek
 
OK, I can't see what your files are actually called, so I can't guarantee that this would work, but here's a suggestion. You may have to twiddle it a bit, but this should get you started.

Code:
#!/bin/csh

set number = 1

foreach file (`ls filename.0[a-z][a-z]`)
  mv $file filename.`printf %03i $number `
  @ number ++
end

The %03i passed to printf means format the value of number ($number) as an integer (i) padded to a width of 3 characters (3) using 0's instead of spaces (0). If that isn't the format you're after, that's the part you'll need to fiddle with.

And of course I don't know if what's in the foreach statement actually matches the names of your files, so you'll need to adjust that part too.

Anyway, hope that helps.

edit: I'm not sure where the ' characters at the beginning and end are coming from - ignore them...
 
Here's a pretty perl script to do what you want, this should handle and format of letters, no matter how long they get.

#!/usr/bin/perl

#
# Make sure args are right, ie: foo.pl /tmp foo will sort all files in
# /tmp that start with "foo"
if($#ARGV != 1) { die "Usage: $0 directory fileprefix\n"; }

opendir(DIR,"$ARGV[0]") || die "Can't open directory $ARGV[0]: $!\n";
@files=grep { /^$ARGV[1]/ } readdir(DIR);

$x=0;
foreach(sort @files) {
chomp;
($first,$second) = /(.*)\.(.+)/;
$newname=sprintf("%s.%03d",$first,$x++);

print "Moving $_ -> $newname\n";
`mv $ARGV[0]/$_ $ARGV[0]/$newname`;
}

Brian
 
YES. Thank you very very much, Scruffy and Brian! You did it!

I will use the code in my Applescript Studio program called
Split & Concat for its update 1.3 and I will put mention both your
names in the about box. The update is to be expected end of this week at www.versiontracker.com/macosx/. I hope you like the program.

Again: THANK YOU!!

Loek
 
Back
Top