cjd143SD cjd143SD - 1 month ago 12
Perl Question

using perl File::Copy to rename a file extension

How do I use

File::Copy
to rename a file extension?

So far, I can add an extension. What I need to do is replace the file extension instead.

Example:
myfilename.txt
to
myfilename.dat


My code:

use strict;
use warnings;
use File::Copy;

my ($oldfn) = qw (myfilename.txt);
my $newfn = $oldfn . ".dat";

rename($oldfn, $newfn)
or die("Can't rename: $!\n");


Result:
myfilename.txt.dat

Answer

Use File::Basename's fileparse method to find the suffix, then do a search/replace.


#!/usr/bin/env perl

use strict;
use warnings;

use feature qw(say);
use File::Basename qw(fileparse);

my $oldfilename = "/foo/bar/baz.txt";

my($filename, $directories, $suffix) = fileparse($oldfilename,qr/\.[^.]*$/);

$filename =~ s/\.$suffix$//;

my $newfilename = $filename.".dat";

say "New filename is:".$newfilename;
say "New fullpath is:".$directories.$newfilename;

exit 0;

Output:

$ ./basename.pl
New filename is:baz.dat
New fullpath is:/foo/bar/baz.dat