AWK:用头将CSV到汇总表 [英] AWK: Converting CSV with Headers to Summary Table

查看:207
本文介绍了AWK:用头将CSV到汇总表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要记录100+ CSV据文件,这些文件的格式,包括样本数据。我想这样做的是采取以下格式的CSV:

I have a need to document 100+ CSV files as far as the format of those files and including sample data. What I would like to do is take a CSV of the following format:

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

和将其转换为:

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

这可能与AWK?从下面我举的例子,你会看到我想作为一个降价表进行格式化。我有它目前移调与标题行

Is this possible with AWK? From my example below, you will see I am trying to format as a markdown table. I have it currently transposing the header row with

#!/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  {}

不过,我不知道现在该怎么使用数据的第一行,标题后显示样本数据?

But I am not sure now how to use the first row of data, after the header to display the sample data?

推荐答案

AWK 是数据分析的工具。你可以尝试这样的:

awk is the right tool for data parsing. You can try something like:

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

这篇关于AWK:用头将CSV到汇总表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆