提取文本并写入Perl中的新文件

时间:2012-06-12 19:20:41

标签: string perl file text extract

简单地说,我想从文件中提取文本,并使用Perl将该文本保存到新文件中。

到目前为止,这是我的代码:

#!/usr/local/bin/perl

use warnings;
use strict;
use File::Slurp;
use FileHandle;

use Fcntl qw(:DEFAULT :flock :seek); # Import LOCK_* constants

my $F_IN = FileHandle->new("<$ARGV[0]");
my $F_OUT = FileHandle->new(">PerlTest.txt");

while (my $line = $F_IN->getline) {
    $line =~ m|foobar|g;
    $F_OUT->print($line);
    # I want to only copy the text that matches, not the whole line.
    # I changed the example text to 'foobar' to avoid confusion.
}

$F_IN->close();
$F_OUT->close();

显然,它正在复制这条线。如何从文件中提取和打印特定文本,而不是整行?

3 个答案:

答案 0 :(得分:3)

如果每行只能发生一次:

while (<>) {
   print "$1\n" if /(thebigredpillow)/;
}

如果每行可以多次发生:

while (<>) {
   while (/(thebigredpillow)/g) {
      print "$1\n";
   }
}

用法:

script file.in >file.out

答案 1 :(得分:2)

您可以使用捕获括号来获取匹配的字符串:

while (my $line = $F_IN->getline) {
    if ($line =~ m|(thebigredpillow)|) {
        $F_OUT->print("$1\n");
    }
}

请参阅perldoc perlre

答案 2 :(得分:1)

#!/usr/local/bin/perl

use warnings;
use strict;
use IO::All;

my @lines = io($ARGV[0])->slurp;

foreach(@lines) {
    if(/thebigredpillow/g) {
        $_ >> io('PerlTest.txt');
    }
}