2012-08-22 22 views
1

我有兩個csv文件F1和F2的行數相同,我想通過比較F2中的文件F1和F2來提取更改/添加的行。使用shell或diff命令提取兩個csv文件中的修改和添加的行

我試過差分命令,但我可以看到變化。我怎樣才能讀取模式並從F2中提取行?

F1(文件1):

1234,Joe,pieter,[email protected],male,22 
1235,Shally,Jonse,[email protected],female,24 
1235,Harry,poter,[email protected],male,21 
1235,Helen,Jairag,[email protected],female,21 
2585,Dinesh,Jairag,[email protected],female,21 

F2(文件2):執行

1234,Joe,pieter,[email protected],male,22 
1235,Shally,Jonse,[email protected],female,24 
1235,Harry,Potter,[email protected],male,21 
1235,Helen,Jairag,[email protected],female,21 

命令:

diff F2 F1 

停止放:

3c3 
< 1235,Harry,Potter,[email protected],male,21 
--- 
> 1235,Harry,poter,[email protected],male,21 
4a5 
> 2585,Dinesh,Jairag,[email protected],female,21 

在文件F3的預期輸出:

1235,Harry,poter,[email protected],male,21 
2585,Dinesh,Jairag,[email protected],female,21 
+0

你的問題不是很清楚,你可以添加預期的輸出嗎? – themel

+0

謝謝,我已經添加了預期的輸出, –

回答

3
diff --changed-group-format='%<' --unchanged-group-format='' file1 file2 
+0

謝謝,它幫助提取行並寫入一個新文件 –

+0

這是真棒 – Rob

1

我明白,要提取更改/來自文件2添加的行
因此,在您的示例中,File2中只有一個更改的行,File2中沒有添加行。
diff的基本呼叫模式爲diff old new,輸出告訴您需要執行哪些操作才能更新old。因此要了解File2中的不同之處,您可以將其用作第二個參數。我會建議使用-u選項diff。這使您可以從文件2的每一行需要被改變/第一POS:

diff -u File1 File2 

File1中添加了 +

--- File1 2012-08-22 11:30:07.000000000 +0200 
+++ File2 2012-08-22 11:30:25.000000000 +0200 
@@ -1,5 +1,4 @@ 
1234,Joe,pieter,[email protected],male,22 
1235,Shally,Jonse,[email protected],female,24 
-1235,Harry,poter,[email protected],male,21 
+1235,Harry,Potter,[email protected],male,21 
1235,Helen,Jairag,[email protected],female,21 
-2585,Dinesh,Jairag,[email protected],female,21 

現在僅篩選與+開始,除了線前兩個條件:

diff -u data1 data2 | \ 
    awk 'NR > 2 && $0 ~ /^+/ {print substr($0,2)}' 

1235,Harry,Potter,[email protected],male,21 

或者其他方式輪:

diff -u data2 data1 | \ 
    awk 'NR > 2 && $0 ~ /^+/ {print substr($0,2)}' 

1235,Harry,poter,[email protected],male,21 
2585,Dinesh,Jairag,[email protected],female,21 
+0

謝謝Theodros,這個解決方案也幫助我解決問題 –

相關問題