如何将包含键/值对的文件转换为CSV?

时间:2016-12-05 17:56:00

标签: awk

我有以下文本文件:

$ cat abc.txt
URL: bbc.com
Address:        10.10.10.5#53
Address: 1.1.1.1
Address: 6.6.6.6
URL: cdn.com
Address:        10.10.10.10#53
Address: 2.2.2.2
URL: ngo.com
Address:        10.10.10.5#53
Address: 3.3.3.3
Address: 4.4.4.4
Address: 5.5.5.5

我想生成以下输出:

URL:           Server          Resolved      
bbc.com        10.10.10.5#53    1.1.1.1,6.6.6.6
cdn.com        10.10.10.10#53   2.2.2.2
ngo.com        10.10.10.5#53    3.3.3.3,4.4.4.4,5.5.5.5

我试过了:

awk 'ORS=($1 ~ "URL:")?",":"\n"' abc.txt

但它并没有给我我想要的东西。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我现在没有时间考虑这个问题,但从这开始就看看你是否可以解决其余问题:

$ awk -v OFS='\t' '
     /URL/ { printf "%s%s%s", (NR>1?ORS:""), $2, OFS; c=0; next }
     { printf "%s%s", $2, (c++?",":OFS) }
     END { print "" }
' abc.txt
bbc.com 10.10.10.5#53   1.1.1.1,6.6.6.6,
cdn.com 10.10.10.10#53  2.2.2.2,
ngo.com 10.10.10.5#53   3.3.3.3,4.4.4.4,5.5.5.5,

答案 1 :(得分:0)

我的想法是URL:用作RS,因此我们可以从abc.txt获取三条记录。然后只打印一条记录的奇数字段。希望它可以帮助你。  :)

$ cat  abc.awk
BEGIN{
    RS="URL:";
}

{
    for(i=1;i<=NF;i+=2)
    {
        if (i<=3)
            printf("%s\t", $i)
        else if (i>3 && i<NF)
            printf("%s, ", $i)
        else
            printf("%s\n", $i)
    }
}

$ awk -f abc.awk abc.txt
bbc.com 10.10.10.5#53   1.1.1.1, 6.6.6.6
cdn.com 10.10.10.10#53  2.2.2.2
ngo.com 10.10.10.5#53   3.3.3.3, 4.4.4.4, 5.5.5.5