【问题标题】:Searching for Files with specific Regex in filename in Perl在 Perl 的文件名中搜索具有特定正则表达式的文件
【发布时间】:2012-01-01 11:51:39
【问题描述】:

大家好,我想知道如何在 perl 中搜索文件。

现在我有一行信息,我用制表符作为分隔符存储到数组中。 (使用拆分)这些数组包含我要在目录中搜索的文件名的存根文本。例如 Engineering_4.txt 在我的数组中只是“Engin”。

如果有两个不同的文件...Engineering_4 和 Engineering_5,它会在这两个文件中搜索内容并从其中一个文件中提取我需要的信息(只有 1 个包含我想要的信息)。我想我的脚本必须搜索并存储所有匹配的文件名,然后搜索每个文件。

我的问题是如何在与 Perl 中的正则表达式匹配的目录中搜索文件?还有一种方法可以限制我要搜索的文件类型。例如,我只想搜索“.txt”文件。

谢谢大家

【问题讨论】:

    标签: regex perl file search


    【解决方案1】:

    您可以使用<glob> 运算符的glob 函数来执行此操作。

    while (<Engin*.txt>) {
     print "$_\n";
    }
    

    【讨论】:

      【解决方案2】:

      我想既然你已经知道目录,你可以打开它并阅读它,同时过滤它:

      opendir D, 'yourDirectory' or die "Could not open dir: $!\n";
      my @filelist = grep(/yourRegex/i, readdir D);
      

      【讨论】:

        【解决方案3】:

        glob 函数在提供通配符表达式时返回匹配文件的数组。

        这意味着文件也可以在处理前sort-ed:

        use Sort::Key::Natural 'natsort';
        
        foreach my $file ( natsort glob "*.txt" ) {  # Will loop over only txt files
        
            open my $fh, '<', $file or die $!; # Open file and process
        }
        

        【讨论】:

          【解决方案4】:

          您也可以使用 File::Find 模块:

          #!/usr/bin/env perl
          use strict;
          use warnings;
          use File::Find;
          my @dirs = @ARGV ? @ARGV : ('.');
          my @list;
          find( sub{
              push @list, $File::Find::name if -f $_ && $_ =~ m/.+\.txt/ },
              @dirs );
          print "$_\n" for @list;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多