使用 BASH 和 AWK 创建 HTML 表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11486756/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an HTML table with BASH & AWK
提问by jdorfman
I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is:
我在创建 html 表以显示文本文件中的统计数据时遇到问题。我确信有 100 种方法可以更好地做到这一点,但它是:
(The comments in the following script show the outputs)
(以下脚本中的注释显示了输出)
#!/bin/bash
function getapistats () {
    curl -s http://api.example.com/stats > api-stats.txt
    awk {'print '} api-stats.txt > api-stats-int.txt
    awk {'print '} api-stats.txt > api-stats-fqdm.txt
}
# api-stats.txt example
#    992 cdn.example.com
#    227 static.foo.com
#    225 imgcdn.bar.com
# end api-stats.txt example
function get_int () {
    for i in `cat api-stats-int.txt`;
        do echo -e "<tr><td>${i}</td>";
    done
}
function get_fqdn () {
    for f in `cat api-stats-fqdn.txt`;
        do echo -e "<td>${f}</td></tr>";
    done
}
function build_table () {
echo "<table>";
echo -e "`get_int`" "`get_fqdn`";
#echo -e "`get_fqdn`";
echo "</table>";
}
getapistats;
build_table > api-stats.html;
# Output fail :|
# <table>
# <tr><td>992</td>
# <tr><td>227</td>
# <tr><td>225</td><td>cdn.example.com</td></tr>
# <td>static.foo.com</td></tr>
# <td>imgcdn.bar.com</td></tr>
# Desired output:
# <tr><td>992</td><td>cdn.example.com</td></tr>
# ...
回答by
This is reasonably simple to do in pure awk:
这在纯 awk 中相当简单:
curl -s http://api.example.com/stats > api-stats.txt
awk 'BEGIN { print "<table>" }
     { print "<tr><td>"  "</td><td>"  "</td></tr>" }
     END   { print "</table>" }' api-stats.txt > api-stats.html
Awk is really made for this type of use.
Awk 确实是为这种用途而设计的。
回答by geirha
You can do it with one awk at least.
你至少可以用一个 awk 来完成。
curl -s http://api.example.com/stats | awk '
    BEGIN{print "<table>"} 
    {printf("<tr><td>%d</td><td>%s</td></tr>\n",,)}
    END{print "</table>"}
' 
回答by Zoltán Haindrich
this can be done w/ bash ;)
这可以用 bash 来完成;)
    while read -u 3 a && read -u 4 b;do
      echo $a$b;
    done 3</etc/passwd 4</etc/services
but my experience is that usually it's a bad thing to do things like this in bash/awk/etc
但我的经验是,在 bash/awk/etc 中做这样的事情通常是一件坏事
the feature i used in the code is deeplyburried in the bash manual page...
我在代码中使用的功能深深地隐藏在 bash 手册页中......
i would recommend to use some real language for this kind of data processing for example: (ruby or python) because they are more flexible/readable/maintainable
我建议使用一些真正的语言来处理这种数据,例如:(ruby 或 python)因为它们更灵活/可读/可维护

