AWK 将 CSV 转换为 HTML 表

cyc*_*ion 4 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
Run Code Online (Sandbox Code Playgroud)

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

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>
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一些事情,但我遇到了一些编译错误......

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

小智 5

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

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

$ chmod +x csv_to_html.awk
$ ./csv_to_html.awk table.csv > table.html
Run Code Online (Sandbox Code Playgroud)

代码:

#!/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>"
}
Run Code Online (Sandbox Code Playgroud)