Batch Rename Files Using Perl

In Perl, batch file renaming can be achieved by using the rename function. Here is a simple example code for changing the file extension from .txt to .dat for all files in a specified directory.

use strict;
use warnings;

my $dir = '/path/to/directory/';

opendir(my $dh, $dir) or die "Cannot open directory: $!";

while (my $file = readdir($dh)) {
    next if $file =~ /^\./;  # skip hidden files
    next unless $file =~ /\.txt$/;  # only process files with .txt extension

    my $old_name = $dir . $file;
    my $new_name = $file;
    $new_name =~ s/\.txt$/.dat/;

    rename($old_name, $dir . $new_name) or die "Cannot rename file: $!";
}

closedir($dh);

Please replace /path/to/directory/ in the code above with the directory path of the files whose names you want to change, then run the code to change all .txt file extensions to .dat. Remember to backup your files before running the code to avoid any unexpected situations.

bannerAds