【问题标题】:Read lines from a file and skip to next line if pattern matches in perl如果 perl 中的模式匹配,则从文件中读取行并跳到下一行
【发布时间】:2014-01-23 09:25:12
【问题描述】:

我正在尝试从文件中读取行并将输出写入另一个文件。我正在使用 open 来实现这一点。但我无法从第一个文件中清除一些不需要的行。 问题来了:

我有一个包含以下行的文本文件

Project1_Employees
Matt Stone
Trey parker
Eric Cartman
Kenny

Project2_Employees
Stan
Matt Stone
Trey Parker
Kyle

我正在使用我的代码对名称进行排序并打印 uniq 名称。但我无法删除 Project1_Employees 和 Project2_Employees 行。这只是文本文件的一部分。有数百行这样的行。

open(FH, '<employeenames.txt');
next if (<FH> =~ m/Employees/);
open(OFH, ">sortedemployee.txt");
my %seen;
print OFH sort grep !$seen{$_}++, <FH>;
close(OFH);
close(FH); 

我正在寻找的输出是

Eric Cartman
Kenny
Kyle
Matt Stone
Stan
Trey parker

我想使用 open 来执行此操作,因为我有一个要求。

【问题讨论】:

  • 如果可以切换,这在 shell 中会非常简单。
  • @BroSlow uniq 需要排序输入
  • @mpapec 对,排序很简单。例如grep -v '_Employees\|^$' file | sort -f | uniq -i 几乎完全符合 OP 的要求

标签: perl


【解决方案1】:
open(FH,  '<', 'employeenames.txt') or die $!;
open(OFH, '>', "sortedemployee.txt") or die $!;
my %seen;
print OFH sort grep { !$seen{$_}++ and !/Employees/ } <FH>;

【讨论】:

    【解决方案2】:

    希望这段代码能帮助您更轻松地理解这个过程。

    #!/usr/bin/perl
    use utf8;
    use strict;
    use warnings;
    
    sub write_special_line {
        open my $file_handler, '<', 'test_file' or die;
        open my $new_handler, '>', 'write_test' or die;
        my $sign;
        my ($hash, @names);
        while (my $row = <$file_handler>) {
            if ($row =~ /Project\d+_Employees/) {
                next;
            } else {
                $hash->{$row} += 1;
                if ($hash->{$row} <= 1) {
                    push @names, $row;
                }
            }
        }
        close $file_handler;
        my @sorted = sort {lc($a) cmp lc($b)} @names;
        for my $name (@sorted) {
            print $new_handler $name;
        }
        close $new_handler;
    }
    
    write_special_line();
    

    【讨论】:

      【解决方案3】:

      已经有一些好的 perl 答案,但如果您不只是在练习 perl,我不会使用 perl 来进行简单的文件操作。使用类似 gnu grep 的东西,例如

      $ grep -v '_Employees\|^$' employeenames.txt | sort -f | uniq -i > sortedemployee.txt
      $ cat sortedemployee.txt
      Eric Cartman
      Kenny
      Kyle
      Matt Stone
      Stan
      Trey parker
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        相关资源
        最近更新 更多