AWK:将带头的CSV转换为汇总表

时间:2014-03-13 00:58:37

标签: csv awk

我需要记录100多个CSV文件,直到这些文件的格式并包含样本数据。我想做的是采用以下格式的CSV:

Name, Phone, State
Fred, 1234567, TX
John, 2345678, NC

并将其转换为:

Field | Sample
---   | ----
Name  | Fred
Phone | 1234567
State | TX

AWK可以实现吗?从下面的示例中,您将看到我正在尝试格式化为降价表。我现在用

转置标题行
#!/usr/bin/awk -v RS='\r\n' -f
BEGIN { printf "| Field \t| Critical |\n"}
{
    printf "|---\t|---\t|\n"
    for (i=1; i<=NF; i++) {print "|", toupper($i), "| sample |"}
}
END  {}

但我现在不确定如何使用第一行数据,在标题后显示样本数据?

2 个答案:

答案 0 :(得分:1)

awk是用于数据解析的正确工具。您可以尝试以下方式:

awk '
BEGIN { FS=", "; OFS=" | " }
NR==1 {
    for(tag = 1; tag <= NF; tag++) {
        hdr[tag] = sprintf ("%-7s", $tag)
    }
    next
}
{
    for(fld = 1; fld <= NF; fld++) {
        data[NR,fld] = $fld
    }
}
END {
    print "Field   | Sample\n------- | -------";
    for(rec = 2; rec <= NR; rec++) {
        for(line = 1; line <= NF; line++) {
            print hdr[line], data[rec,line]
        }
    }
}' file

<强>输出

Field   | Sample
------- | -------
Name    | Fred
Phone   | 1234567
State   | TX
Name    | John
Phone   | 2345678
State   | NC

答案 1 :(得分:1)

这是使用awk进行更简单的方法 无需将所有内容存储在数组中,然后在最后打印。

awk -F", " 'NR==1{split($0,a,FS);print "Field   | Sample\n------- | -------";next} {for (i=1;i<=NF;i++) printf "%-8s| %s\n",a[i],$i}' file
Field   | Sample
------- | -------
Name    | Fred
Phone   | 1234567
State   | TX
Name    | John
Phone   | 2345678
State   | NC

工作原理:

awk -F", " '                            # set field separator to ","
NR==1{                                  # if first line do:
    split($0,a,FS)                      # split first line to an array named "a" to get the labels 
    print "Field   | Sample"            # print header
    print "------- | -------"           # print separator
    next}                               # prevents nothing more run for first line
    {                                   # for all lines except first do:
    for (i=1;i<=NF;i++)                 # loop trough all element in line
        printf "%-8s| %s\n",a[i],$i     # print data for every element
    }
' file