cjd143SD
cjd143SD

Reputation: 869

Using Perl's 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. I need to 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

Upvotes: 2

Views: 4992

Answers (3)

sidyll
sidyll

Reputation: 59277

A little regex would do the job:

($new = $old) =~ s/[^.]+$/dat/;
rename $old, $new or die "Can't rename: $!\n";

Upvotes: 1

TLP
TLP

Reputation: 67900

A simple regex will suffice:

$newfn = $oldfn;
$newfn =~ s/\.txt$/.dat/i;

Oh, you might also want to do:

use File::Copy qw(move);

...

move($oldfn, $newfn) or die...

Otherwise you are using Perl's built-in function rename.

Upvotes: 1

bot403
bot403

Reputation: 2162

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

Upvotes: 2

Related Questions