我有一个名为 test1.txt 的输入文件,其中包含成百上千个文件名。
test word document.docx
...
...
amazing c. document.docx
1. 2. 3.45 document.docx
...
...
我想做的是从字符串中获取文件名和扩展名。对于大多数文件名,只有一个点,因此我可以使用点作为分隔符来获取文件名和分机号。但问题是某些文件名在文件名中有多个点。我不知道如何从中获取扩展名和文件名。
这是我的 perl 代码。
use strict;
use warnings;
print "Perl Starting ... \n\n";
open my $input_filehandle1, , '<', 'test1.txt' or die "No input Filename Found test1.txt ... \n";
while (defined(my $recordLine = <$input_filehandle1>))
{
chomp($recordLine);
my @fields = split(/\./, $recordLine);
my $arrayCount = @fields;
#if the array size is more than 2 then we encountered multiple dots
if ($arrayCount > 2)
{
print "I dont know how to get filename and ext ... $recordLine ... \n";
}
else
{
print "FileName: $fields[0] ... Ext: $fields[1] ... \n";
}
}#end while-loop
print "\nPerl End ... \n\n";
1;
这是输出:
Perl Starting ...
FileName: test word document ... Ext: docx ...
I dont know how to get filename and ext ... amazing c. document.docx ...
I dont know how to get filename and ext ... 1. 2. 3.45 document.docx ...
Perl End ...
我想得到什么
FileName: test word document ... Ext: docx ...
FileName: amazing c. document ... Ext: docx ...
FileName: 1. 2. 3.45 document ... Ext: docx ...
最佳答案
这就是File::Basename是为了。
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use File::Basename;
while (<DATA>) {
chomp;
my ($name, undef, $ext) = fileparse($_, '.docx');
say "Filename: $name ... Ext: $ext";
}
__DATA__
test word document.docx
amazing c. document.docx
1. 2. 3.45 document.docx
三件值得解释的事情。
- 我使用
DATA
文件句柄,因为这是一个演示,它比使用单独的输入文件更容易。 fileparse()
返回目录路径作为第二个值。由于此数据不包含目录路径,因此我忽略了该值(通过将其分配给undef
)。fileparse()
的第二个(及后续)参数是要分离的扩展列表。您只在示例数据中使用一个扩展名。如果您有更多扩展名,您可以将它们添加到“.docx”之后。
关于perl如何获取文件名和扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905684/