Remove file extension and path from a string in Perl

Chris picture Chris · Sep 8, 2010 · Viewed 65.1k times · Source

I want to obtain a file name without its path (if it is part of the string) and also the extension.

For example:

/path/to/file/fileName.txt     # results in "fileName"
fileName.txt                   # results in "fileName"
/path/to/file/file.with.periods.txt    # results in "file.with.periods" 

So basically, I want to remove anything before and including the last "/" if present and also the last "." along with any meta characters after it.

Sorry for such a novice question, but I am new to perl.

Answer

rafl picture rafl · Sep 8, 2010

For portably getting the basename of a file given a full path, I'd recommend the File::Basename module, which is part of the core.

To do heuristics on file extensions I'd go for a regular expression like

(my $without_extension = $basename) =~ s/\.[^.]+$//;