Cerberus
Cerberus

Reputation: 51

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

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.

Upvotes: 0

Views: 534

Answers (1)

Ed Morton
Ed Morton

Reputation: 203674

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.

Upvotes: 1

Related Questions