Convert content of file to HTML

Hi
I have file like this:

jack black 104
daniel nick 75
lily harm 2
albert 5

and need to convert it into the html table like this:

NO.......name....family..... id
1...........jack.....black.....104
2..........daniel....nick.......75
3..........albert.................5

i mean script that when I ran on this file automatically insert html tags and put them in correct place in html table.

here is my script

awk 'BEGIN {
        x = 0;
        print "<table border="10">"
    }
    {
        if (NF == 1){
            print "<tr ><td colspan="2">"$i"</td>";
            print "</tr>"
        } else {
            if (x == 1){
                x++;
                print "<tr><td>"$i"</td>"
            } else {
                x = 0;
                print "<td>"$i"</td></tr>"
            }
        }
    }
    END {
        print "</table>"
    }' a.html > ui/index.html

Hi, what have you tried so far?

dear Scrutinizer add to the post.

Thanks,

Hi variable i is not set anywere,

Try something like this to start with:

awk '
  BEGIN {
    print "<table border="10">"
  }
  NF==1{
    print "<tr ><td colspan=\"2\"> "$i" </td></tr>"
    next
  }
  NF==2 {
    $3=$2
    $2=""
  }
  {
    s="<tr><td>" NR "</td>"
    for(i=1; i<=NF; i++) 
      s=s "<td>" $i "</td>"
    s=s "</tr>"
    print s
  }
  END {
    print "</table>"
  }
' file

or perhaps simply:

awk '
  BEGIN {
    print "<table border="10">"
  } 
  NF==1 { 
    print "<tr ><td colspan=\"2\"> "$i" </td></tr>"
    next
  }
  NF==2{
    $3=$2
    $2=""
  }
  { 
    printf "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n", NR,$1,$2,$3
  } 
  END {
    print "</table>"
  }
' file

You can also do it in shell..

1 Like

Thank you dear Scrutinizer,
But problem is some of cells are empty and I want put empty cell instead of replace next cell with it.
e.g look at number 3

NO.......name....family..... id
1...........jack.....black.....104
2..........daniel....nick.......75
3..........albert.................5

You need to normalize the data first. Since line 3 contains only two fields instead of three, how can we know that albert is not supposed to be under column family or that 5 is not column family ? You have to give us some criteria to normalize first.

An example for a criteria could be:
If a line contains only two fields the empty field correspond to the family column.

However, that could have the side effect that if a line has

daniel nick

The rule will make it

NO.......name....family..... id
0.......daniel........nick