Perl ファイル名一括変更:リネーム処理の基本と実践
Perlでファイル名を一括変更するには、rename関数を使用します。以下は.txtから.datにすべてのファイル名を変更する簡単なサンプルコードです。
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);
上記のコード中の/path/to/directory/の部分を、ファイル名を変更したいディレクトリのパスに置き換えて、このコードを実行するとすべての.txtファイルの拡張子が.datに変更されます。コードを実行する前に、ファイルのバックアップを取っておくことをお忘れなく、万が一の事態に備えてください。