AWK脚本:将单列XML转换为CSV

时间:2018-01-14 19:07:15

标签: xml csv awk pivot

我是AWK脚本的新手,需要有关将一组单列数据转换为旋转(?)CSV集的建议。

数据类似于:

<field1>A</field1>
<field2>B</field2>
<field3>C</field3>
<field1>1</field1>
<field2>2</field2>
<field3>3</field3>

...我想生成:

field1,field2,field3
A,B,C
1,2,3

非常感谢任何帮助和建议。

谢谢!

1 个答案:

答案 0 :(得分:2)

tst.awk:

BEGIN{FS="[</>]"; OFS=","}
!($5 in label2colNr) {
    label2colNr[$5] = ++numCols
    colNr2label[numCols] = $5
}
{
    colNr = label2colNr[$5]
    val[++numRows[colNr],colNr] = $3
    maxRows = (numRows[colNr] > maxRows ? numRows[colNr] : maxRows)
}
END {
    for (colNr=1; colNr <= numCols; colNr++) {
        printf "%s%s", colNr2label[colNr], (colNr<numCols ? OFS : ORS)
    }

    for (rowNr=1; rowNr <= maxRows; rowNr++) {
        for (colNr=1; colNr <= numCols; colNr++) {
            printf "%s%s", val[rowNr,colNr], (colNr<numCols ? OFS : ORS)
        }
    }
}

用法:awk -f tst.awk file.xml

输出:

field1,field2,field3
A,B,C
1,2,3

致以:Ed Mortonhttps://stackoverflow.com/a/48252943/3776858