views:

474

answers:

4

HI,
I have a string that looks like

/dir/dir1/filename.txt

I want to replace the "filename.txt" with some other name leaving the "/dir/dir1" intact so after the replace the string would look like

/dir/dir1/newfilename.txt

how would I do that using RegExp in Perl considering that I don't know the value of "filename"

Many Thanks

P.S : "filename.txt" and "newfilename.txt" have been used for the purpose of making things simple when asking the question the original filename will vary.

+5  A: 
$filename =~ s%/[^/]*$%/newfilename.txt%;
  • s%...%...% - use % as the delimiter, so you can use / in the pattern
  • / - match a slash
  • [^/]* - and any string not containing a slash
  • $ - up to the end of the string
Alnitak
@Alnitak Thank you very much for your reply, one more thing please, if I just wanted to extract "filename.txt" from "/dir/dir1/filename.txt" instead of replacing it, what would I use in the regexp
Anand
use "if ($filename =~ m%...%)" and wrap the original [^/]* bit with brackets { i.e. ([^/]*) } and then it'll be available as $1
Alnitak
+11  A: 

I would suggest against using regular expressions to fiddle with filenames/paths. Directory Separators, valid/invalid characters vary from one platform to the next and can be a problem to hunt down. I advise you try File::Spec to extract the filename and then replace it with whatever you want

Gurunandan
+9  A: 

Regular expressions is the wrong tool for your problem. Regexes are fantastic, work most of the time but are not always the cleanest (readability) or fastest solution.

I would propose to use the classic File::Basename. In contrast with File::Spec, File::Basename is a core module (nothing to install!) and really easy to use:

    use File::Basename;

    my $basename = basename($fullname,@suffixlist);
    my $dirname  = dirname($fullname);

My favorite use:

    my $filename = basename($path);
+1  A: 

Try something like this...

#!/usr/bin/perl

use strict;

my $string = "/dir/dir1/filename.txt";
my @string = split /\//, $string;
$string[-1] = "newfilename.txt";
print join "/", @string;
bichonfrise74