2012-10-22 184 views
0

我有一個文件a.txt,並且我有文件b.txt.I正在讀取這兩個文件。如何在perl中追加文件

讓我們假設A.TXT有:

Apple is a fruit. 
I like java. 
I am an human being. 
I am saying hello world. 

比方說b.txt有

I am the planet earth 

現在我試圖尋找在A.TXT如特定的字符串:我是人。如果我找到這一行。我想在b.txt到a.txt.My輸出文件的內容追加看起來應該有些這樣的事

Apple is a fruit. 
I like java. 
I am the planet earth---->appended 
I am an human being. 
I am saying hello world. 

我嘗試以下,但它不是幫助

open (FILE1 , "a.txt") 
my (@fpointer1) = <FILE>; 
close FILE1 

open (FILE2 , "b.txt") 
my (@fpointer1) = <FILE>; 
close FILE2 

#Open the a.txt again, but this time in write mode 
open (FILE3 , ">a.txt") 
my (@fpointer1) = <FILE>; 
close FILE3 

foreach $line (@fpointer1) { 

if (line to be searched is found) 
--> Paste(Insert) the contents of file "b.txt" read through fpointer2 

} 
+0

這是無效的Perl。大多數表達式之後你缺少';'。總是用'嚴格使用'和'使用警告'來啓動你的文件。你也應該使用「open」和「lexical」文件句柄的三參數版本。 – dgw

回答

1

這裏有一個快速和骯髒的工作例如:

use warnings; 
use 5.010; 

open FILE, "a.txt" or die "Couldn't open file: $!"; 
while (<FILE>){ 
$string_A .= $_; 
} 

open FILE, "b.txt" or die "Couldn't open file: $!"; 
while (<FILE>){ 
$string_B .= $_; 
} 
close FILE; 

$searchString = "I am an human being."; 


$resultPosition = index($string_A, $searchString); 

if($resultPosition!= -1){ 

$endPosition = length($string_A)+length($string_B)-length($searchString); 

$temp_String = substr($string_A, 0, $resultPosition).$string_B." "; 


$final_String =$temp_String.substr($string_A, $resultPosition, $endPosition) ; 
} 
else {print "String not found!";} 

print $final_String; 

有可能是這樣做的更有效的方法。但你可以有一個想法。

0

這裏爲例

use strict; 

open(A, ">>a.txt") or die "a.txt not open"; 
open(B, "b.txt") or die "b.txt not open"; 

my @text = <B>; 
foreach my $l (@text){ 
     if ($l =~ /I am the planet earth/sg){ 
       print A $&; 
     } 
} 

我認爲,像這樣......