2015-02-24 18 views
1

好吧,我應該感到羞愧對於這一點,但我無法理解AWK是如何工作的?更新值文件對文件B A使用參考 - 返回

前幾天我張貼this question有關如何用文件B作爲參考來替換文件A上的字段的問題(兩個文件都有匹配的ID以供參考)。

但接受的答案是正確的之後(感謝埃德!)我掙扎如何做到這一點使用這個以下模式:

文件

{"test_ref":32132112321,"test_id":12345,"test_name":"","test_comm":"test", "null_test": "true"} 
{"test_ref":32133321321,"test_id":12346,"test_name":"","test_comm":"test", "test_type": "alfa"} 
{"test_ref":32132331321,"test_id":12347,"test_name":"","test_comm":"test", "test_val": 1923} 

文件B

{"test_id": 12345, "test_name": "Test values for null"} 
{"test_id": 12346, "test_name": "alfa tests initiated"} 
{"test_id": 12347, "test_name": "discard values"} 

預期結果:

{"test_ref":32132112321,"test_id":12345,"test_name":"Test values for null","test_comm":"test", "null_test": "true"} 
{"test_ref":32133321321,"test_id":12346,"test_name":"alfa tests initiated","test_comm":"test", "test_type": "alfa"} 
{"test_ref":32132331321,"test_id":12347,"test_name":"discard values","test_comm":"test", "test_val": 1923} 

我嘗試了一些原始解決方案的改動,但沒有成功。那麼,根據之前發佈的問題,我如何才能用這種新模式獲得相同的結果?

PS:一個重要的提示,對文件中的行並不總是具有相同的長度提前

非常感謝。

編輯:

試圖發表Wintermute的解決方案後,作用似乎它好好嘗試與具有行工作:收到

{"test_ref":32132112321,"test_id":12345,"test_name":"","test_comm":"test", "null_test": "true","modifiers":[{"type":3,"value":31}{"type":4,"value":33}]} 

錯誤。

error: parse error: Expected separator between values at line xxx, column xxx 
+0

在fileB中,冒號應該在引號的內部還是外部(即''test_id:「12345'或''test_id」:12345')? – 2015-02-24 17:11:06

+0

@EdMorton外面,我會修正它,謝謝你注意:) – 2015-02-25 17:26:01

回答

3

解析JSON使用awk或sed的不是,這不是解析XML與他們一個好主意,同樣的原因,一個好主意:根據行sed的作品,而JSON不是線爲主。 awk在模糊的表格數據上工作,而JSON不是模糊的表格。人們不希望他們的JSON工具在良性地方插入換行符時破壞。

相反,請考慮使用面向JSON處理的工具,如jq。在這種特殊情況下,你可以使用

jq -c -s 'group_by(.test_id) | map(.[0] + .[1]) | .[]' a.json b.json > c.json 

這裏jq吸食(-s)輸入文件轉換成JSON對象,這些羣體的數組,test_id,將它們合併和解壓的陣列。 -c意味着緊湊的輸出格式,因此結果中的每個JSON對象都會在輸出中的一行中結束。

+0

完美!也正要回答這樣的問題,但需要找出正確的'jq'語法。謝謝你舉個例子! :) – hek2mgl 2015-02-24 11:35:14

+0

@Wintermute看來,group_by將被刪除:根據https://stedolan.github.io/jq/manual/ – 2015-02-26 22:54:06

+0

而被'group'取代,所以你可以使用它。只是我的jq版本顯然對於'group'來說太老了。 – Wintermute 2015-02-27 08:52:07