这是我的问题,假设我有一个file1.txt内容文件
:
abc..
def..
ghi..
def..
Run Code Online (Sandbox Code Playgroud)
和file2.txt内容的第二个文件:
xxx..
yyy..
zzz..
Run Code Online (Sandbox Code Playgroud)
现在我想复制开始"高清"的所有线file1.txt对file2.txt和追加后"YYY ......"行file2.txt
xxx...
yyy...
def...
def...
zzz...
Run Code Online (Sandbox Code Playgroud)
我对perl很新,我已经尝试为此编写简单的代码,但最终输出只附加在文件的末尾
#!/usr/local/bin/perl -w
use strict;
use warnings;
use vars qw($filecontent $total);
my $file1 = "file1.txt";
open(FILE1, $file1) || die "couldn't open the file!";
open(FILE2, '>>file2.txt') || die "couldn't open the file!";
while($filecontent = <FILE1>){
if ( $filecontent =~ /def/ ) {
chomp($filecontent);
print FILE2 $filecontent ."\n";
#print FILE2 $filecontent ."\n" if $filecontent =~/yyy/;
}
}
close (FILE1);
close (FILE2);
Run Code Online (Sandbox Code Playgroud)
perl程序的输出是
xxx...
yyy...
zzz...
def...
def...
Run Code Online (Sandbox Code Playgroud)
我使用临时文件.
use strict;
use warnings;
my $file1 = "file1.txt";
my $file2 = "file2.txt";
my $file3 = "file3.txt";
open(FILE1, '<', $file1) or die "couldn't open the file!";
open(FILE2, '<', $file2) or die "couldn't open the file!";
open(FILE3, '>', $file3) or die "couldn't open temp file";
while (<FILE2>) {
print FILE3;
if (/^yyy/) {
last;
}
}
while (<FILE1>) {
if (/^def/) {
print FILE3;
}
}
while (<FILE2>) {
print FILE3;
}
close (FILE1);
close (FILE2);
close (FILE3);
rename($file3, $file2) or die "unable to rename temp file";
Run Code Online (Sandbox Code Playgroud)