【问题标题】:perl how to get filename and extensionperl如何获取文件名和扩展名
【发布时间】: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


【解决方案1】:

这就是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

值得解释的三件事。

  1. 我使用DATA 文件句柄,因为这是一个演示,它比单独的输入文件更容易。
  2. fileparse() 返回目录路径作为第二个值。由于此数据不包括目录路径,因此我忽略了该值(通过将其分配给 undef)。
  3. fileparse() 的第二个(和后续)参数是要分离的扩展列表。您在示例数据中只使用一个扩展名。如果您有更多扩展名,您可以在“.docx”之后添加它们。

【讨论】:

  • 戴夫,这是一个很好的答案。只要我知道文件 ext 是什么,它就可以很好地工作。如果我遇到一个我没有添加的分机,那么文件解析将不起作用。
【解决方案2】:

不要使用split

只使用常规模式匹配:

#! /usr/bin/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);

    if ($recordLine =~ /^(.*)\.([^.]+)$/) {
      print "FileName: $1 ... Ext: $2 ... \n";
    }

}#end while-loop

print "\nPerl End ... \n\n"; 

1;

Regexper 解释了regular expression

【讨论】:

  • 如果你使用$_而不是$recordLine :-)
  • 这是我最终使用的正则表达式 /(.*)\.(\w+)$/
  • @DaveCross 当然,但这不是Code Review。 ;-)
猜你喜欢
  • 2014-04-14
  • 1970-01-01
  • 2019-03-22
  • 2019-05-21
  • 2012-07-23
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多