首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AWK将CSV转换为HTML表格

AWK将CSV转换为HTML表格
EN

Stack Overflow用户
提问于 2016-11-02 08:58:05
回答 2查看 6K关注 0票数 3

只是在linux上胡闹,在AWK上闲逛。如何将CSV格式的文件转换为HTML格式的文件?例如..。这是我加载到我的shell中的信息...

代码语言:javascript
复制
user$ cat table.csv
Ep#,Featured Film,Air date
211,First Spaceship on Venus,12/29/90
310,Fugitive Alien,08/17/91
424,Manos: The Hands of Fate,01/30/93

然后在运行代码之后,这就是应该输出的内容。

代码语言:javascript
复制
user$ csv2html.awk table.csv
<html><body><table>
<tr>
<th>Ep#</th>
<th>Featured Film</th>
<th>Air date</th>
</tr>
<tr>
<td>211</td>
<td>First Spaceship on Venus</td>
<td>12/29/90</td>
</tr>
<tr>
<td>310</td>
<td>Fugitive Alien</td>
<td>08/17/91</td>
</tr>
<tr>
<td>424</td>
<td>Manos: The Hands of Fate</td>
<td>01/30/93</td>
</tr>
</table></body></html>

我已经尝试了一些事情,但我有一些编译错误…

代码语言:javascript
复制
#!/bin/awk
print "<tr>
for( i = 1; i <= NF; i++)
     print "<td> "$i" </td"
#print "</tr>"
EN

回答 2

Stack Overflow用户

发布于 2016-11-02 20:08:05

在AWK中有很多方法可以做到这一点,但我首选的方法是下面的代码。我在代码中包含了一些解释作为注释。希望这能有所帮助!

要在命令行界面上运行,请将代码保存在一个名为'csv_to_html.awk‘的文件中,并以'table.csv’作为参数执行:

代码语言:javascript
复制
$ chmod +x csv_to_html.awk
$ ./csv_to_html.awk table.csv > table.html

代码:

代码语言:javascript
复制
#!/bin/awk -f

# Set field separator as comma for csv and print the HTML header line
BEGIN {
    FS=",";
    print "<html><body><table>"
}
# Function to print a row with one argument to handle either a 'th' tag or 'td' tag
function printRow(tag) {
    print "<tr>";
    for(i=1; i<=NF; i++) print "<"tag">"$i"</"tag">";
    print "</tr>"
}
# If CSV file line number (NR variable) is 1, call printRow fucntion with 'th' as argument
NR==1 {
    printRow("th")
}
# If CSV file line number (NR variable) is greater than 1, call printRow fucntion with 'td' as argument
NR>1 {
    printRow("td")
}
# Print HTML footer
END {
    print "</table></body></html>"
}
票数 3
EN

Stack Overflow用户

发布于 2016-11-03 08:33:18

另一个类似的awk

代码语言:javascript
复制
    BEGIN{header = "<html><body><table>"; print header}
         {c = NR == 1 ? "th" : "td";
          OFS = et(c) bt(c);
          $1 = $1;
          print wrap("tr", wrap(c,$0)) }
      END{gsub("<","</",header); print header }

    function wrap(t, v) { return bt(t) v et(t)}
    function bt(t) {return "<" t ">"}
    function et(t) {return "</" t ">"}

使用OFS插入相应的xml标记,而不是循环元素。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40370908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档