如何将以下日志文​​件转换为CSV类型文件?

时间:2013-08-23 03:40:14

标签: shell sed grep export-to-csv tr

我有一个格式如下的日志文件:

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

2 个答案:

答案 0 :(得分: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 :(得分: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