Main Page Content
Renaming Files With Perl
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
Make all the files in the directory end with .html instead of .txt.
rename 's/txt$/html/' *
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
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.