Sunday, January 22, 2012

Perl Program to rename files from format1 (name1, name2, ... name999) to format2 (name001, name002, .. name999)


#!/usr/bin/perl

# Perl Program to rename files from format1 (name1, name2, ... name999) to format2 (name001, name002, .. name999)
# First argument is string with which the file names begin
# Must navigate to the directory where changes are to be made.

use strict;
use warnings;

my $number_of_files_updated = 0;
my $filenumber = "";
my $newfilenumber = "";

opendir (DIR, ".") or die "could not open dir: $!";
LINE: while (my $file = readdir(DIR)) {
    # skip . and .. files
next LINE if($file eq ".." || $file eq ".");

# 1. get current file number
$filenumber = substr($file, length($ARGV[0]));
$newfilenumber = $filenumber;
       # 2. compute a new file number
if(length($filenumber) eq 1){
$newfilenumber = "0000".$filenumber;
# 3. rename file
rename($file,$ARGV[0].$newfilenumber);
$number_of_files_updated++;
}
elsif (length($filenumber) eq 2){
$newfilenumber = "000".$filenumber;
# 3. rename file
rename($file,$ARGV[0].$newfilenumber);
$number_of_files_updated++;
}
elsif (length($filenumber) eq 3){
$newfilenumber = "00".$filenumber;
# 3. rename file
rename($file,$ARGV[0].$newfilenumber);
$number_of_files_updated++;
}
elsif (length($filenumber) eq 4){
$newfilenumber = "0".$filenumber;
# 3. rename file
rename($file,$ARGV[0].$newfilenumber);
$number_of_files_updated++;
}
# we will do nothing for other files
}
closedir(DIR);
print "$number_of_files_updated files updated.\n"

Program in action