Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 43 ยท Projects

Project: Batch File Renamer

Build a safe batch file renamer in Perl: glob files, rename them with a regex, parse options with Getopt::Long, add a dry-run mode and refuse to overwrite.

Renaming a hundred photos by hand is boring, and renaming them with a careless script can destroy files. This project builds a small command-line tool that renames files with a regular expression and is careful by default: it can show what it would do first, and it never overwrites an existing file unless you say so.

Along the way you will combine regular expressions, directory work and the core module Getopt::Long, which turns --dry-run and --from on the command line into Perl variables.

Perl is not installed on this site, so the Perl code is read-only. Its output below was captured from a real run on Perl 5.42. The interactive examples are Bash stand-ins that follow the same logic with sed, mv and a few tests.

The design

Safe renaming rules

Dry run first Print the plan, change nothing.
No overwrites Skip when the target exists.
No collisions Two files must not map to one name.
Clear report Say what happened to every file.

A rename tool should never surprise you.

1 / 2

The tool takes these options:

Option Meaning
--from REGEX Pattern to look for in each file name (required)
--to TEXT Replacement text (required)
--dir DIR Directory to work in (default .)
--glob PATTERN Which files to consider (default *)
--dry-run or -n Show the plan, rename nothing
--force Allow overwriting existing files
--help Print usage

Parsing options with Getopt::Long

GetOptions reads @ARGV, removes the options it understands and stores their values. Passing a hash reference as the first argument collects everything into one hash, so $opt{from} holds the value of --from. A specification such as 'dir=s' means "takes a string", 'dry-run|n' means a flag with a short alias.

PERL
use v5.36;
use Getopt::Long;
use File::Basename qw(basename);
use File::Spec;
use File::Glob qw(bsd_glob);

my %opt = (dir => '.', glob => '*');
GetOptions(\%opt, 'dir=s', 'glob=s', 'from=s', 'to=s', 'dry-run|n', 'force', 'help')
    or die "Try --help\n";

if ($opt{help} || !defined $opt{from} || !defined $opt{to}) {
    print <<"USAGE";
Usage: ren.pl --from REGEX --to TEXT [--dir DIR] [--glob PATTERN] [--dry-run] [--force]
USAGE
    exit($opt{help} ? 0 : 2);
}

GetOptions returns false when it meets an unknown option, so or die stops the program with a message. Exit status 2 signals a usage error to the shell, while 0 after --help means success. The key 'dry-run' contains a dash, so you read it with quotes: $opt{'dry-run'}.

Compiling the regex safely

The pattern comes from the user, so it might be invalid. Compile it once with qr// inside eval. If it fails, report the problem instead of crashing in the middle of the work:

PERL
my $from = eval { qr/$opt{from}/ } // die "Bad regex '$opt{from}': $@";

Running with --from '(' printed:

TEXT
Bad regex '(': Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at ../ren.pl line 17.

The replacement text is used as plain text. A $1 in --to is not expanded, which is deliberate: evaluating user input as code (s///ee) is a security risk. If you need captures, add a separate, explicit feature for them.

Finding the files

glob is the classic way to expand a pattern like *.jpg, but the built-in version splits its argument on spaces, so a directory called my photos breaks it. File::Glob's bsd_glob treats the whole string as one pattern, and File::Spec->catfile joins the directory and the pattern in a portable way.

PERL
my @files = sort grep { -f } bsd_glob(File::Spec->catfile($opt{dir}, $opt{glob}));

grep { -f } keeps only plain files, using the file test from Directories and File Tests, and sort makes the order predictable, so the output is the same on every run.

The rename loop

For each file we compute the new name, then decide what to do. Order matters here: the checks come before the rename.

PERL
my (%target_seen, $renamed, $skipped);

for my $path (@files) {
    my $name = basename($path);
    (my $new = $name) =~ s/$from/$opt{to}/g;
    next if $new eq $name;

    my $dest = File::Spec->catfile($opt{dir}, $new);

    if ($target_seen{$dest}++) {
        say "SKIP  $name -> $new (another file already maps there)";
        $skipped++;
        next;
    }
    if (-e $dest && !$opt{force}) {
        say "SKIP  $name -> $new (exists, use --force)";
        $skipped++;
        next;
    }

    if ($opt{'dry-run'}) {
        say "WOULD  $name -> $new";
    } elsif (rename $path, $dest) {
        say "OK    $name -> $new";
        $renamed++;
    } else {
        warn "FAIL  $name -> $new: $!\n";
        $skipped++;
    }
}
say "Done: ", $renamed // 0, " renamed, ", $skipped // 0, " skipped.";

Several small ideas are packed in there:

  • (my $new = $name) =~ s/$from/$opt{to}/g; copies the name and edits the copy. Modern Perl also offers s///r, which returns the changed copy: my $new = $name =~ s/$from/$opt{to}/gr;.
  • $target_seen{$dest}++ is false the first time and true after that. It catches two sources that would collide on one destination before either is renamed.
  • -e $dest && !$opt{force} is the overwrite guard. rename replaces an existing file silently on most systems, so the check has to be ours.
  • rename returns false and sets $! on failure (permissions, a read-only disk), and we report it with warn.
  • In a dry run the same decisions are made as in a real run, so the plan you read is the plan you get. Only the final action is skipped.
  • $renamed // 0 prints zero when the counter was never touched, so no "uninitialized" warning appears.

Seeing it work

The test folder held IMG 001.jpg, IMG 002.jpg, holiday 01.jpg, holiday-01.jpg and notes.txt. First a dry run:

TEXT
$ perl ren.pl --from '\s+' --to '-' --glob '*.jpg' --dry-run
WOULD  IMG 001.jpg -> IMG-001.jpg
WOULD  IMG 002.jpg -> IMG-002.jpg
SKIP  holiday 01.jpg -> holiday-01.jpg (exists, use --force)
Done: 0 renamed, 1 skipped.

The plan looks right, and holiday 01.jpg is protected because holiday-01.jpg already exists. Now the real run, then the same run with --force:

TEXT
$ perl ren.pl --from '\s+' --to '-' --glob '*.jpg'
OK    IMG 001.jpg -> IMG-001.jpg
OK    IMG 002.jpg -> IMG-002.jpg
SKIP  holiday 01.jpg -> holiday-01.jpg (exists, use --force)
Done: 2 renamed, 1 skipped.

$ perl ren.pl --from '\s+' --to '-' --glob '*.jpg' --force
OK    holiday 01.jpg -> holiday-01.jpg
Done: 1 renamed, 0 skipped.

The second run found nothing more to do for the two files that were already renamed, because their names no longer contain whitespace. That makes the tool idempotent: running it again is harmless.

Bash stand-ins

The same plan fits in a few lines of Bash. First the dry run: nothing is changed, and the listing at the end proves it.

Bash Dry run in Bash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Now the real run, with the safety check kept in place. The -- after mv stops a file name that starts with a dash from being read as an option, and the quotes protect names that contain spaces.

Bash Real rename in Bash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Ideas to extend it

  • Add --undo: write each old -> new pair to a log file and read it back in reverse.
  • Number files with a counter: sprintf('photo-%03d.jpg', ++$n).
  • Recurse into folders with File::Find (see Directories and File Tests).
  • Test the renaming rule as its own subroutine with Test::More (see Testing).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a dry-run mode do?

    A dry run goes through the same checks and prints the plan, so you can review it before anything is changed.
  2. 2. Why does the tool check -e $dest before calling rename?

    On most systems rename overwrites the target without warning, so the safety check has to be written by you.
  3. 3. What does GetOptions(\%opt, 'dry-run|n', 'dir=s') do?

    GetOptions parses @ARGV according to the specifications and fills the hash. A spec ending in =s takes a string value.
  4. 4. Why is the replacement text used as plain text and not evaluated with s///ee?

    The ee modifier evaluates the replacement as code, which is dangerous for input you do not control.

Summary

  • Getopt::Long turns command-line options into Perl values; check its return value and print usage on errors.
  • Compile user-supplied patterns with qr// inside eval so a typo gives a clear message.
  • Use bsd_glob and File::Spec->catfile for file lists that may contain spaces.
  • Be safe by default: dry run, no overwrites without --force, and detect two files mapping to one name.
  • Make the tool idempotent so running it twice does no harm.

Next project: Link Checker and Scraper.