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をインストールしています。この Web サイトで他の多くの例を検索して試しましたが、うまくいきませんでした。残念ながら、私は Perl の完全な専門家ではありません。

sedも使用する例があれば、Cygwin sedも持っています。

4

3 に答える 3

6

これはコマンドライン バージョンです。

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

コマンドラインオプションの説明:

-i.bak : 入力ファイルに作用し、拡張子が .bak のバックアップ バージョンを作成します。

-p : 入力ファイルの各行をループして、その行を $_ に入れ、各反復後に $_ を出力します

-e : 入力ファイルの各行に対してこのコードを実行します

Perl のコマンド ライン オプションはperlrunに記載されています。

コードの説明:

データ行 ($_ 内) が「icecream: sunday\n」の場合、行の前に「icecream: saturday\n」を追加します。

次に、 $_ を出力するだけです (これは -p フラグで暗黙的に行われます)。

于 2012-11-30T10:50:10.940 に答える
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 に答える
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 に答える