Skip to content
November 7, 2008 / edeustace

Batch rename files in OS X with Perl

I was rummaging around to see if OS X had a rename command like Linux, but there doesn’t appear to be one. I found a perl script online that I modified to do renaming for me. Feel free to copy and modify.

Note: apologies about the formatting, I’m new to wordpress and don’t know why its not preserving my indentation. I tried using the code tag, but no joy.

Say you have a folder like so:

perl ~/myFolderWithFilesToAppend Suffix

Will create:

#!/usr/bin/perl -w

use strict;
use File::Copy;

sub recurse

my($path) = $_[0];
my($suffix) = $_[1];

## append a trailing / if it’s not there
$path .= ‘/’ if($path !~ //$/);

for my $file (glob($path.’*’))
if( -d $file)
recurse($file, $suffix);

my @splitArray = split(/./, $file );
my $newfile = “$splitArray[0]$suffix.$splitArray[1]”;
copy($file, $newfile) or die “File cannot be copied: $file”;

print “rename files will add $ARGV[1] to the file (but before the suffix)n”;
my $numArgs = $#ARGV + 1;
foreach my $argnum (0 .. $#ARGV)
print “$ARGV[$argnum]n”;

recurse($ARGV[0], $ARGV[1]);
print “donen”;



Leave a Comment
  1. chaosfarmer / Nov 7 2008 2:10 pm

    find * -exec mv {} {}.new \;

  2. edeustace / Nov 7 2008 4:55 pm

    Thanks chaosfarmer,
    is this a shell command? could you give an example?

  3. chaosfarmer / Nov 7 2008 5:40 pm

    find is a unix utility.

    if you have a directory that looks like this

    and you want to add the extension .old to each file you would change to that directory and run:

    find * -exec mv {} {}.old \;
    find : the command
    * : all files
    -exec : run a command on each file found
    {} : variable, name of the file found
    ().old : variable, name of the file found with .old hooked on the end
    \; : end the exec command

    and you would end up with

    find can do a whole lot of things, so google find or man find on your machine.

  4. edeustace / Nov 9 2008 12:22 am

    Cheers chaosfarmer, you are a scholar and a gent.
    I wanted to maintain the suffix and append a word to the end.. so:
    would become:

    but i’ll check out find and see what it can do.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: