Web Hosting Talk







View Full Version : Shell scripting loops


nmluan
03-07-2004, 12:25 AM
I would like to write a small shell scripts to rename all my files to ADDON_oldfilename###.jpg

I need to rename each and every file in the directory. All the name has the same name but different incremental ids like this:
filename_123.jpg and filename_124.jpg...

Anybody know how to do this?

Thanks a lot.

thedavid
03-07-2004, 12:41 AM
Moved to programming as they're all about that stuff here ;)

OIS
03-07-2004, 04:24 AM
It's not the prettiest script ever written, but it works:


#!/usr/bin/perl

my $dir = shift;

if (!$dir) {
print "Usage: rename.pl /directory/with/files/\n\n";
exit 1;
}

@a = `ls $directory`;


$i=1;
foreach (@a) {
chomp();
/^(.*?)\.(.*)$/;
`mv $dir$_ $dir$1_$i.$2`;
$i++
}


Save as rename.pl and make executable:


# chmod o+x rename.pl


The script takes a single parameter: the path to the directory containing your files. It assumes that each file will be named in the format name.ext and that there will be no sub-directories. The script should be saved in a different directory or it will rename itself.


# ./rename.pl /home/user/test/