2015-02-11 71 views
-3

文件1用线块替换线的块文件1:file2中

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 

我想,以替换 'ABC' file1中与行在file2中有'abc'的行。我是新来的sed,awk等任何帮助表示赞赏。 我尝试了cat file1 <(sed '/$r = abc;/d' file2) > newfile等,但这只是简单地将file1复制到新文件。我也不想生成一个新文件,但只编辑file1。
期望的输出:
(处理)的file1:

一个XYZ 1 2 4
一个XYZ 1 2 3
一个ABC 3 8 9
一个ABC 6 2 7
一个KLM 9 3 1
荷航9 8 3
一个TLC 3 9 3

+1

请提供更多信息 – 2015-02-11 08:05:05

+1

我编辑了一些更多细节的问题 - 这是否足够? – 2015-02-11 08:19:31

+0

您可以在示例文件中显示(并解释)您的预期输出吗? – jas 2015-02-11 09:12:50

回答

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。

+0

谢谢但它没有对file1做任何修改 - 我在问题中运行完全相同的文件 – 2015-02-11 13:38:20

+0

将输出重定向到另一个文件,然后通过file1移动它:'gawk yaddayadda file2 file1> file1.new && mv file1.new file1' – Wintermute 2015-02-11 13:39:41

+0

仍然是原始文件1。我尝试了gawk yaddayadda file2 file1> file1.new,然后检查其差异; diff file1 file1.new没有区别,没有变化 – 2015-02-11 13:47:55

相关问题