This script will rename all files with one extension to another extension. Example: all files in a given directory that end with .php will be renamed to end with .txt.
- Download the program and instructions
The only change you might have to make is if you’re on a Linux machine and Perl is not at /usr/bin/perl, but somewhere else, in which case you would need to change the first line to contain the proper path. I’ve not tested this program on a Windows box.
#!/usr/bin/perl
# Renames file extensions
#
# Syntax:
# perl extensionChanger.pl --from=FIRST_EXTENSION --to=SECOND_EXTENSION
# Example use:
# perl extensionChanger.pl --from=html --to=php
# Optional:
# Specify a directory to work in. Defaults to PWD.
# --dir=DIRECTORY
# Example use:
# perl extensionChanger.pl --from=exe --to=pl --dir=tmp
#
# Sarah; 2005-12-18
use Getopt::Long;
GetOptions(
"from=s" => \$ext1,
"to=s" => \$ext2,
"dir=s" => \$dir
);
if ($ext1 eq "" or $ext2 eq "") {
print "Syntax:\n";
print "\tperl extensionChanger.pl --from=FIRST_EXTENSION --to=SECOND_EXTENSION\n\n";
print "Example:\n";
print "\tperl extensionChanger.pl --from=txt --to=php\n\n";
print "Optional:\n";
print "\tSpecify a directory to work in. Defaults to PWD.\n";
print "\t--dir=DIRECTORY\n\n";
print "Example:\n";
print "\tperl extensionChanger.pl --from=exe --to=pl --dir=tmp\n";
exit;
} else {
if ($dir eq "") {
$dir = ".";
}
opendir(DIR, $dir) || die "Could not open directory for reading.";
# Get an array of all files with the old extension that are in the given directory
@files = grep(/\.$ext1$/, readdir(DIR));
if ($files[0] eq "") {
print "There are no files of extension '$ext1' ";
if ($dir eq ".") {
print "in PWD";
} else {
print "in $dir";
}
print ".\n";
} else {
# For every file with the old extension in the given directory...
foreach $file (@files) {
print "$file ";
if ($dir ne ".") {
print "in $dir/ ";
}
# Remove the current extension from the $file variable
$file =~ s/\.$ext1//g;
# Rename the file to have the new extension
$error = `mv $dir/$file.$ext1 $dir/$file.$ext2`;
print "is now $file.$ext2\n";
# If there were errors, print them
if ($error ne "") {
print "E: $error\n";
}
}
}
closedir(DIR);
}
2 Comments
Would be much simpler to do something like:
perl -e ‘for (@ARGV) { ($new = $_) =~ s/\.html$/.php/; rename $_, $new }’ *.html
In fact, I can nearly type that from the command line. There’s a script called “rename” in the core distribution that does this.
Awesome! Thanks. I need to learn how to write much shorter Perl code… The “poetry” I’ve seen on perlmonks and other examples of code, such as the DeCSS stuff, shows me that I’m being way inefficient with my Perl.