Awk 用文件2中的行块替换文件1中的行块
文件1: 文件2:Awk 用文件2中的行块替换文件1中的行块,awk,sed,Awk,Sed,文件1: 文件2: 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中有“abc”的行替换文件1中有“abc”的行。我是sed、awk等的新手,非常感谢您的帮助。 我尝试了cat file1 newfile和其他方法,但这个方法只是将file1复制到newfile。我也不想生成新文件,只想编辑文件1。 期望输出: 已处理文件1: a x
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中有“abc”的行替换文件1中有“abc”的行。我是sed、awk等的新手,非常感谢您的帮助。
我尝试了cat file1 newfile和其他方法,但这个方法只是将file1复制到newfile。我也不想生成新文件,只想编辑文件1。
期望输出:
已处理文件1:
a xyz 12 4
a xyz 12 3
a abc 389
a abc 627
荷航931
荷航983
使用GNU awk的tlc 3 9 3,您可以使用以下技巧:
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
使用记录分隔符[^\n]*abc[^\n]*\n+,将输入文件拆分为由行块分隔的记录,其中包含abc。那么
gawk -v RS='([^\n]* abc [^\n]*\n)+' 'NR == FNR { save = RT; nextfile } FNR == 1 { printf "%s", $0 save; next } { printf "%s", $0 RT }' file2 file1
注意,这使用了几个GNU扩展,因此,mawk无法使用它。请提供更多信息我编辑了问题,并提供了更多详细信息-这足够吗?您能给出示例文件显示并解释您的预期输出吗?所需的输出添加感谢,但它没有对文件1做任何更改-我在问题中运行了完全相同的文件将输出重定向到另一个文件,然后将其移到文件1上:gawk yaddayada file2 file1>file1.new&&mv file1.new file1,直到它成为原始文件1。我尝试了gawk yaddayada file2 file1>file1.new,然后检查了差异;diff file1 file1.new且无差异,未进行任何更改。请复制/复制。现在修复了第二个块的FNR==1,而不是NR==1。愚蠢的错误。
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", $0 save # print it with the saved record terminator
next # from file2, and get the next record
}
{ # from then on, just echo.
printf "%s", $0 RT
}