Skip to page content or Skip to Accesskey List.

Work

Main Page Content

Renaming Files With Perl

Rated 4.21 (Ratings: 7)

Want more?

  • More articles in Code
 
Picture of dmah

Dean Mah

Member info

User since: 05 Jun 1999

Articles written: 25

Have you ever wanted to rename more than one file at a time? Have you ever wanted to be able to rename a group of files based on a regular expression? Well the script below will let you do just that.

The Code

#!/usr/local/bin/perl

#

# Usage: rename perlexpr [files]

($regexp = shift @ARGV) || die "Usage: rename perlexpr [filenames]

";

if (!@ARGV) {

@ARGV = <STDIN>;

chomp(@ARGV);

}

foreach $_ (@ARGV) {

$old_name = $_;

eval $regexp;

die $@ if $@;

rename($old_name, $_) unless $old_name eq $_;

}

exit(0);

The Explanation

Save the above code into a file called rename. Make sure that the permissions are set correctly so that you can execute the script. Also check to make sure that your Perl interpreter is in /usr/local/bin. If Perl is somewhere else, you'll need to change the first line to point to where Perl is installed on your system.

To use the script you use:

rename perlexpr [files]

where perlexpr is the substitution operator, i.e., s///. You can actually pass any Perl expression through to perlexpr allowing you to do more complex file renaming actions. The files argument is a list of filenames that you want to change. You can leave the files argument out and the script will take a list of names from STDIN.

The Examples

  1. Make all the files in the directory end with .html instead of .txt.

    rename 's/txt$/html/' *
  2. Change all the files prefixed with the text mah and suffixed with .new to be suffixed with .old instead.

    rename 's/new$/old/' mah*.new
  3. Hide every file in the directory by prefixing the filename with a .

    rename 's/(.+)/\.$1/' *

The possibilities are endless. You should be careful however as you are dealing with regular expressions. You should be as specific as possible when specifying your patterns otherwise you may rename a file in a way that you had not anticipated.

For instance, take the first example. If you had typed:

rename 's/txt/html/' *

(notice the missing $ in the pattern?) and you had a file named newtxt.txt, the script would rename the file to newhtml.txt which might not have been what you wanted.

Hopefully this script will be useful to you. If you have any problems or questions, you can e-mail them to me at dean.mah@gmail.com.

Founding member of evolt.org.
Dean Mah

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.org Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.