2012-11-29 47 views
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專家。

我也有Cygwin sed,如果有一個例子也使用sed。

+3

向我們展示您的嘗試。 – mob

回答

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; 
+0

嗨,謝謝。
不幸的是,似乎沒有工作。我收到消息「無法在@INC中查找IO/All.pm(@INC包含:C:/ Perl64/site/lib C:/ Perl64/lib 。)at callpl.pl line 1. BEGIN failed - 編譯在callpl.pl第1行中止。「 – user1864091

+0

@ user1864091您需要安裝CPAN中的IO :: All模塊。您應該可以通過從命令行運行'perl -MCPAN -e「install IO :: All來執行此操作,如果您使用的是Active State perl,則可以使用Perl Package Manager實用程序來執行此操作。 – David

+0

@ user1864091更新了腳本並刪除了使用任何perl模塊的要求。 – David

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; 
5

這是一個命令行版本。

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

的命令行選項說明:

-i.bak:作用於輸入文件,創建與擴展的備份版本.bak的

-p:將輸入文件的每一行循環放入$ _並在每次迭代後打印$ _

-e:執行該代碼輸入文件

Perl的命令行選項在perlrun記錄每一行。

的代碼說明:

如果數據線($ _)是 「冰淇淋:星期日\ n」 個,那麼前加上 「冰淇淋:星期六\ n」 來的行。

然後只需打印$ _(這是用-p標誌隱式完成的)。

相關問題