【发布时间】:2019-04-30 00:00:01
【问题描述】:
我有一个名为 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 ...
【问题讨论】:
-
使用正则表达式:regex101.com/r/L9fLGX/1
-
File::Basename 很方便。
-
@PhxDev 太棒了!谢谢你。我唯一的问题是,正则表达式每行在数组中生成 3 个项目,而不是两个。数组中的第一个值始终为空。不知道为什么,但它有效。让我发布一个解决方案
-
数组中的第一个元素是
$0,表示所有行。$1用于文件名,$2用于扩展名。请将我的回答标记为有用;)
标签: perl