用 file2 中的一行替换 file1 中的一行

replace a block of lines in file1 with a block of lines in file2

文件 1:

a xyz 1 2 4  
a xyz 1 2 3  
a abc 3 9 7  
a abc 3 9 2  
a klm 9 3 1  
a klm 9 8 3  
a tlc 3 9 3  

文件 2:

a xyz 9 2 9  
a xyz 8 9 2   
a abc 3 8 9  
a abc 6 2 7  
a tlk 7 8 9  

我想用文件 2 中具有 'abc' 的行替换文件 1 中具有 'abc' 的行。我是 sed、awk 等的新手。感谢任何帮助。 我尝试了 cat file1 <(sed '/$r = abc;/d' file2) > newfile 等,但这个只是将 file1 复制到 newfile。我也不想生成新文件,只想编辑 file1。
期望的输出:
(已处理)文件 1:

一xyz 1 2 4
一个 xyz 1 2 3
一个 abc 3 8 9
一个 abc 6 2 7
荷兰航空 9 3 1
荷兰航空 9 8 3
薄层色谱法 3 9 3

使用 GNU awk,你可以使用这个技巧:

gawk -v RS='([^\n]* abc [^\n]*\n)+' 'NR == FNR { save = RT; nextfile } FNR == 1 { printf "%s", [=10=] save; next } { printf "%s", [=10=] RT }' file2 file1

使用记录分隔符 ([^\n]* abc [^\n]*\n)+,这会将输入文件拆分为由包含 " abc " 的行块分隔的记录。那么,

NR == FNR {              # while processing the first given file (file2)
  save = RT              # remember the first record terminator -- the
                         # first block of lines with abc in them
  nextfile               # and go to the next file.
}               
FNR == 1 {                # for the first record in file1
  printf "%s", [=11=] save   # print it with the saved record terminator
  next                   # from file2, and get the next record
}
{                        # from then on, just echo.
  printf "%s", [=11=] RT
}

请注意,这使用了多个 GNU 扩展,因此不适用于 mawk。