【问题标题】:I need help only printing certain lines from a textfile (perl)我需要帮助只打印文本文件(Perl)的某些行
【发布时间】:2012-02-16 15:43:47
【问题描述】:

我一直在寻找答案,但由于我对 perl 很陌生,我可以使用一些帮助来解释我的问题,因为我无法从其他线程中获取答案并调整他们的代码。

我最接近找到最接近解决方案的是: How can I write only certain lines of a file in Perl?

同样的问题,但我只想写以“/”开头的行,这可能吗,如果可能,我该怎么做?

非常感谢任何帮助,在此先感谢!

【问题讨论】:

    标签: perl


    【解决方案1】:

    一个简单的实现可能如下所示:

    while (<>) {
        print $_ if /^\//;
    }
    

    这会在行首 (^) 之后立即查找 /

    如果您想在行首允许一些空格,请将您的正则表达式更改为 /^[[:space:]]*\//

    脚本的其余部分基本上与您所链接的问题相同。

    【讨论】:

      【解决方案2】:

      Perl 也可以在命令行中用于此目的:

      $ perl -lne 'print if /^\//' input.txt > output.txt
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        use strict;
        use warnings;
        
        open my $fhi, '<', $input or die "Can not open file $input: $!";
        while (<$fhi>) {
            print $_ if m/^\//;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-02
          • 2015-03-09
          • 1970-01-01
          • 2022-12-16
          • 2021-10-09
          • 1970-01-01
          • 2013-06-17
          相关资源
          最近更新 更多