从 Perl 中的字符串中删除文件扩展名和路径

发布于 2024-09-18 14:02:38 字数 358 浏览 8 评论 0原文

我想获取一个不带路径的文件名(如果它是字符串的一部分)和扩展名。

例如:

/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" 

所以基本上,我想删除之前的所有内容,包括最后一个“/”(如果存在)以及最后一个“.”。以及其后的任何元字符。

很抱歉提出这样一个新手问题,但我是 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

末骤雨初歇 2024-09-25 14:02:38

为了可移植地获取给定完整路径的文件的基本名称,我建议使用 File: :Basename模块,它是核心的一部分。

为了对文件扩展名进行启发式处理,我会使用正则表达式,例如

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

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/\.[^.]+$//;
赏烟花じ飞满天 2024-09-25 14:02:38

尽管其他人已经做出了回应,但在阅读了 rafl 的回答的基本名称后:

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

似乎可以用一行解决问题。

与其他解决方案相反,是否存在与此相关的任何问题?

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?

满天都是小星星 2024-09-25 14:02:38

假设路径分隔符是'/',可以用一对替换

$name =~ s{^.*/}{};     # remove the leading path  
$name =~ s{\.[^.]+$}{}; # remove the extension

您也可以将其写为单个替换:

$name =~ s{^.*/|\.[^.]+$}{}g;

Assuming that the path separator is '/', you can do it with a pair of substitutions:

$name =~ s{^.*/}{};     # remove the leading path  
$name =~ s{\.[^.]+$}{}; # remove the extension

You can also write that as a single substitution:

$name =~ s{^.*/|\.[^.]+$}{}g;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文