复制一个文件中的选定行,并在选定行后将这些行插入另一个文件中

Emm*_*man 3 perl

这是我的问题,假设我有一个file1.txt内容文件 :

abc.. 
def.. 
ghi.. 
def..
Run Code Online (Sandbox Code Playgroud)

file2.txt内容的第二个文件:

xxx..
yyy..
zzz..
Run Code Online (Sandbox Code Playgroud)

现在我想复制开始"高清"的所有线file1.txtfile2.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)

Pau*_*oub 5

我使用临时文件.

  1. 从FILE2读取并打印所有行(到temp)直到你点击"yyy"
  2. 从FILE1读取并打印所有"def"行(到temp)
  3. 读取并打印(到临时)FILE2的其余部分
  4. 将临时文件重命名为FILE2
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)