【问题标题】:Read the last line of file with data in Perl用 Perl 中的数据读取文件的最后一行
【发布时间】:2021-01-13 21:40:12
【问题描述】:

我有一个要在 Perl 中解析的文本文件。我从文件开头解析它并获取所需的数据。

完成所有这些后,我想读取文件中的最后一行数据。问题是最后两行是空白的。那么如何获取包含任何数据的最后一行呢?

【问题讨论】:

    标签: perl


    【解决方案1】:

    如果文件比较短,从你完成获取数据的地方继续阅读,保留最后一个非空行:

    use autodie ':io';
    open(my $fh, '<', 'file_to_read.txt');
    # get the data that is needed, then:
    my $last_non_blank_line;
    while (my $line = readline $fh) {
        # choose one of the following two lines, depending what you meant
        if ( $line =~ /\S/ ) { $last_non_blank_line = $line }  # line isn't all whitespace
        # if ( line !~ /^$/ ) { $last_non_blank_line = $line } # line has no characters before the newline
    }
    

    如果文件较长,或者您可能在初始数据收集步骤中通过了最后一个非空行,请重新打开它并从末尾读取:

    my $backwards = File::ReadBackwards->new( 'file_to_read.txt' );
    my $last_non_blank_line;
    do {
        $last_non_blank_line = $backwards->readline;
    } until ! defined $last_non_blank_line || $last_non_blank_line =~ /\S/;
    

    【讨论】:

      【解决方案2】:
      perl -e 'while (<>) { if ($_) {$last = $_;} } print $last;' < my_file.txt
      

      【讨论】:

      • 即使是空行也包含一个非空字符串,即\n。你想要if (/\S/) 或类似的。
      • 如果你想保留有空格的行,但跳过没有字符的行,你可以使用while (&lt;&gt;) { chomp; if (length) { ...
      【解决方案3】:

      您可以通过以下方式使用模块File::ReadBackwards

      use File::ReadBackwards ;
      $bw = File::ReadBackwards->new('filepath') or
          die "can't read file";
      while( defined( $log_line = $bw->readline ) ) {
          print $log_line ;
          exit 0;
      }
      

      如果它们为空,只需检查$log_line 是否与\n 匹配;

      【讨论】:

        【解决方案4】:

        如果文件很小,我会将它存储在一个数组中并从最后读取。如果它很大,请使用 File::ReadBackwards 模块。

        【讨论】:

          【解决方案5】:

          这是我的命令行 perl 解决方案的变体:

          perl -ne 'END {print $last} $last= $_ if /\S/' file.txt
          

          【讨论】:

            【解决方案6】:

            没有人提到Path::Tiny。如果文件大小相对较小,您可以这样做:

            use Path::Tiny;
            
            my $file = path($file_name);
            my ($last_line) = $file->lines({count => -1});
            

            CPAN page.

            记住大文件,正如@ysth 所说,最好使用File::ReadBackwards。差异可能很大。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-06-03
              • 2016-07-30
              • 2012-07-22
              • 1970-01-01
              • 2023-01-26
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多