How to read from file and output to html table with AWK

会有一股神秘感。 提交于 2021-02-11 15:47:24

问题


I'm newby in AWK and I know its not a specific question. I just need some advice how should i do this.

Given the following names in a file, author.list:


KOVACS PETER
Kiss Roland
Nagy jolan
Lisztes Tibor
Feher aNDRas
Korma Maria
Akarki Jack

write an AWK program that can read the names from the file and print them to an html table with a three-column format in an output file, output.html. The table should render like this:

    Kovacs Peter     Lisztes Tibor    Akarki Jack
    Kiss Roland      Feher Andras
    Nagy Jolan       Korma Maria

An example execution:

awk -f convert.awk author.list > output.html

Ensure that output.html is a valid html file.


回答1:


Without seeing the HTML you want to generate it's a guess but this might be what you want:

$ cat tst.awk
BEGIN {
    print "<html>"
    print "  <table>"
}
{
    for (i=1; i<=NF; i++) {
        $i = toupper(substr($i,1,1)) tolower(substr($i,2))
    }
    if ( (NR%3) == 1 ) {
        if (NR>1) print "      </tr>"
        print "      <tr>"
    }
    printf "        <td>%s</td>\n", $0
}
END {
    for (i=NR+1; (i%3) != 1; i++) {
        printf "        <td>%s</td>\n", ""
    }
    print "      </tr>"

    print "  </table>"
    print "</html>"
}

.

$ awk -f tst.awk author.list
<html>
  <table>
      <tr>
        <td>Kovacs Peter</td>
        <td>Kiss Roland</td>
        <td>Nagy Jolan</td>
      </tr>
      <tr>
        <td>Lisztes Tibor</td>
        <td>Feher Andras</td>
        <td>Korma Maria</td>
      </tr>
      <tr>
        <td>Akarki Jack</td>
        <td></td>
        <td></td>
      </tr>
  </table>
</html>

The name upper/lower case conversion will fail on names like McDonald or O'Hara or Billy-Bob that don't only have 1 capital letter at the start of the name. If you have to handle that then you need to provide an algorithm.



来源:https://stackoverflow.com/questions/61011422/how-to-read-from-file-and-output-to-html-table-with-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!