2015-02-11 60 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

相關問題