html - AWK 将 CSV 转换为 HTML 表格

标签 html linux csv awk

只是在 Linux 中混混,然后转入 AWK。我将如何将 CSV 格式的文件更改为 HTML 格式的文件。例如...这是我加载到 shell 中的信息...

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

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

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>

我已经尝试了一些与此相关的方法,但我遇到了一些编译错误...

#!/bin/awk
print "<tr>
for( i = 1; i <= NF; i++)
     print "<td> "$i" </td"
#print "</tr>"

最佳答案

在 AWK 中有很多方法可以做到这一点,但我更喜欢使用下面的代码。我在代码中包含了一些解释作为注释。希望这对您有所帮助!

要在 CLI 上运行,请将代码保存在“csv_to_html.awk”等文件中,并以“table.csv”作为参数执行:

$ chmod +x csv_to_html.awk
$ ./csv_to_html.awk table.csv > table.html

代码:

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

关于html - AWK 将 CSV 转换为 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40370908/

相关文章:

javascript - 弹出框阴影也需要用于箭头

php - 通过视觉 Composer 覆盖 CSS 代码

Linux 下 C++ 编译错误

python - 为什么 Python "preemptively"在尝试计算非常大的数字时会挂起?

Ruby 转置 csv

python - 如何计算多个csv文件中数字的平均值?

mysql - HTML5页面用node.js连接mysql数据库

html - CSS动画- "starting from border"如何填写?

linux - Linux 上的 Perl : change locale for subprocesses

带有 sqlalchemy 的 Python Pandas |批量插入错误