2017-05-23 24 views
0

我正在嘗試編寫一個bash腳本來修改從一個MySQL數據庫導出到另一個MySQL數據庫的CSV文件。如何使用bash將字符添加到CSV中每個記錄的可變數量的字段?

輸入文件樣本。

12345,This is a test description,This is a test priority,[1494372600,1494376200,1494546300,1494549900] 
54321,This is a another test description,This is another test priority,[1494956700,1494958500] 

我也可以將它導出爲以下內容,如果它很重要的話。

12345,This is a test description,This is a test priority,1494372600,1494376200,1494546300,1494549900 
54321,This is a another test description,This is another test priority,1494956700,1494958500 

我的目標是讓它看起來像下面這樣。

12345,This is a test description,This is a test priority,[[1494372600,1494376200],[1494546300,1494549900]] 
54321,This is a another test description,This is another test priority,[[1494956700,1494958500]] 

每個記錄中的最後一個字段是對的開始時間和結束時間。這裏的關鍵是每個記錄導出的字段數量取決於每個記錄有多少對開始時間和結束時間。任何幫助,將不勝感激。

謝謝!

回答

0

隨着GNU AWK的第三個參數匹配():

$ awk 'match($0,/(.*)(\[.*)/,a){gsub(/[^,]+,[^,]+/,"[&]",a[2]); $0=a[1] a[2]} 1' file 
12345,This is a test description,This is a test priority,[[1494372600,1494376200],[1494546300,1494549900]] 
54321,This is a another test description,This is another test priority,[[1494956700,1494958500]] 

你需要添加一個變量加SUBSTR()等awks。

+0

這也有效。謝謝! – hstjunk

0

awk來救援! 使用第一格式

awk -F'[' '{n=split($2,a,","); s=FS; 
      for(i=1;i<n;i+=2) s=s FS a[i] "," a[i+1] "]" (i==(n-1)?"":","); 
      print $1 s}' file       

還假設沒有方括號在其他領域。

+0

它工作得很好!非常感謝。 – hstjunk

相關問題