How do I replace part of a string using regexp?

HI,
I have a line that looks like

/dir/dir1/filename.txt

      

I want to replace "filename.txt" with a different name, leaving "/ dir / dir1" intact so after the replacement the line looks like

/dir/dir1/newfilename.txt

      

how can i do this using RegExp in Perl considering i dont know the value of "filename"

Many thanks

PS: "filename.txt" and "newfilename.txt" have been used to simplify the simplest issues when initially changing the filename.

+1


a source to share


4 answers


$filename =~ s%/[^/]*$%/newfilename.txt%;

      



  • s%...%...%

    - use %

    as separator, so you can use /

    in template
  • /

    - match with a trait
  • [^/]*

    - and any line that does not contain a slash
  • $

    - to the end of the line
+7


a source


I suggest against using regex for scripts with names / paths. Directory separators, valid / invalid characters vary from platform to platform and can be a problem to find. I advise you to try File :: Spec to extract the filename and then replace it with whatever you want



+11


a source


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

I would suggest using the classic File :: Basename . Unlike File :: Spec, File :: Basename is the main module (don't install anything!) And very easy to use:

    use File::Basename;

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

      

My favorite usage:

    my $filename = basename($path);

      

+10


a source


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;

      

+1


a source







All Articles