1

简而言之,我想使用 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();

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

4

3 回答 3

3

如果每行只能发生一次:

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

如果每行可能发生多次:

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

用法:

script file.in >file.out
于 2012-06-12T19:27:54.510 回答
2

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

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

请参阅perldoc perlre

于 2012-06-12T19:27:32.663 回答
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');
    }
}
于 2012-06-12T19:30:15.553 回答