1

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.

4 Answers 4

11

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

Sign up to request clarification or add additional context in comments.

Comments

10

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);

Comments

7
$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

2 Comments

@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
use "if ($filename =~ m%...%)" and wrap the original [^/]* bit with brackets { i.e. ([^/]*) } and then it'll be available as $1
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.