2013-08-23 49 views
1

我有格式化這樣的日誌文件:如何將以下日誌文​​件轉換爲CSV類型文件?

timestamp=123; 
data1=value1; 
data2=value2; 
         <-- empty line 
timestamp=456; 
data3=value3; 
data4=value4; 

什麼UNIX命令,我可以用將其轉換爲這種格式:

timestamp=123,data1=value1,data2=value2 
timestamp=456,data3=value3,data4=value4 

回答

1

如何AWK?

#!/bin/bash 

awk ' 
BEGIN { 
    FS = ";"; # $1 will contain everything but the semicolon 
    first_item = 1; 
} { 
    if ($1 == "") { # handle empty line 
      printf "\n"; 
      first_item = 1; 
      next; 
    } 

    if (first_item != 1) { # avoid comma at the end of the line 
      printf ","; 
    } else { 
      first_item = 0; 
    } 

    printf "%s", $1; # print the item 
} END { 
    printf "\n"; 
}' 

如果輸入保存在input.txt中和上面的腳本名爲to_csv.sh, 以下命令將產生所需的輸出:

./to_csv.sh < input.txt 
1

這可能會爲你工作(GNU SED):

sed -r ':a;$!N;s/;\n/,/;ta;s/,(\n)/\1/;$s/;//;P;D' file 

或該:

sed -r ':a;$!N;s/;\n(timestamp)/\n\1/;s/;\n/,/;ta;s/,(\n)/\1/;$s/;//;P;D' file