Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove file extension and path from a string in Perl

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.

like image 773
Chris Avatar asked Sep 08 '10 12:09

Chris


People also ask

How do I get the filename from the path in Perl?

Use the File::Basename module: use File::Basename; ... $file = basename($path);

How do I remove a file extension from a string in bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.

How do I remove a directory extension?

Open File Explorer and click View tab, Options. In Folder Options dialog, move to View tab, untick Hide extensions for known file types option, OK. Then you will se file's extension after its name, remove it.


2 Answers

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/\.[^.]+$//; 
like image 170
rafl Avatar answered Sep 21 '22 09:09

rafl


Although others have responded, after reading a bit on basename per rafl's answer:

($file,$dir,$ext) = fileparse($fullname, qr/\.[^.]*/); # dir="/usr/local/src/" file="perl-5.6.1.tar" ext=".gz" 

Seems to solve the problem in one line.

Are there any problems related with this, opposed to the other solutions?

like image 38
Chris Avatar answered Sep 19 '22 09:09

Chris