3

在文本文件中,我想使用 perl 在另一行文本的每次匹配之前插入一行新文本。

示例 - 我的文件是:

holiday
april
icecream: sunday
jujubee
carefree
icecream: sunday
Christmas
icecream: sunday
towel

...

我想'icecream: saturday'在 'icecream: sunday'行之前插入一行文本。所以之后,文本文件看起来像。:是的,我在搜索和替换模式中都需要冒号。

holiday
april
icecream: saturday
icecream: sunday
jujubee
carefree
icecream: saturday
icecream: sunday
Christmas
icecream: saturday
icecream: sunday
towel
...

我想在 Windows PC 上使用 perl 5.14 来做到这一点。我已经安装了 Perl。我已经在这个网站上搜索并尝试了许多其他示例,但它们对我不起作用,不幸的是我不是 Perl 的完整专家。

如果也有使用 sed 的示例,我也有 Cygwin sed。

4

3 回答 3

6

This is a command-line version.

perl -i.bak -pe '$_ = qq[icecream: saturday\n$_] if $_ eq qq[icecream: sunday\n]' yourfile.txt

Explanation of command line options:

-i.bak : Act on the input file, creating a backup version with the extension .bak

-p : Loop through each line of the input file putting the line into $_ and print $_ after each iteration

-e : Execute this code for each line in the input file

Perl's command line options are documented in perlrun.

Explanation of code:

If the line of data (in $_) is "icecream: sunday\n", then prepend "icecream: saturday\n" to the line.

Then just print $_ (which is done implicitly with the -p flag).

于 2012-11-30T10:50:10.940 回答
2
open FILE, "<icecream.txt" or die $!;
my @lines = <FILE>;
close FILE or die $!;

my $idx = 0;
do {
    if($lines[$idx] =~ /icecream: sunday/) {
        splice @lines, $idx, 0, "icecream: saturday\n";
        $idx++;
    }
    $idx++;
} until($idx >= @lines);

open FILE, ">icecream.txt" or die $!;
print FILE join("",@lines);
close FILE;
于 2012-11-29T18:42:35.137 回答
2

这是使用File::Slurp模块的选项:

use strict;
use warnings;
use File::Slurp qw/:edit/;

edit_file sub { s/(icecream: sunday)/icecream: saturday\n$1/g }, 'data.txt';

还有一个不使用该模块的选项:

use strict;
use warnings;

open my $fhIn,  '<', 'data.txt'          or die $!;
open my $fhOut, '>', 'data_modified.txt' or die $!;

while (<$fhIn>) {
    print $fhOut "icecream: saturday\n" if /icecream: sunday/;
    print $fhOut $_;
}

close $fhOut;
close $fhIn;
于 2012-11-29T18:50:16.490 回答