file1:
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
file2:
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
我想替换那些有' abc'在file1中包含有' abc'在file2中。我是sed,awk等的新手。感谢任何帮助。
我试过了cat file1 <(sed '/$r = abc;/d' file2) > newfile
,但是这个只是将file1复制到newfile。我也不想生成新文件但只编辑file1
期望的输出:
(已处理)file1:
xyz 1 2 4
a xyz 1 2 3
a ab 3 8 9
a ab 6 2 7
a klm 9 3 1
a klm 9 8 3
a tlc 3 9 3
答案 0 :(得分:0)
使用GNU awk,你可以使用这个技巧:
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
使用记录分隔符([^\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", $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
}
请注意,这使用了几个GNU扩展,因此它不适用于mawk。