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.
a source to share
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
a source to share
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);
a source to share