In this example, we use FS – the field separator to set it to the desired delimiter for splitting the line of files into fields. Then, we create the heading of the HTML table in the BEGIN block by fetching the elements of the first record, by checking whether NR==1. Then, the body of the table is created using NR >1, until the last line of the file is read. The following is a sample file named table.txt used here to illustrate the text-to-HTML table conversion, as follows:
$ vi table.txt
NAME:ENGLISH:MATHS:SOCIAL SCIENCE:MUSIC
Sanjay:70:80:65:95
Hitesh:55:72:82:64
Rahul:80:83:65:70
Dhirendra:81:82:83:84
$ vi array2html.awk
BEGIN {
FS =":";
printf "%s%s%s",
"<TABLE cellpadding="1pt" BORDER="2pt" ",
"CELLSPACING="0pt" bgcolor="#ffffff" ",
"bordercolor="#000000"> ";
}
(NR==1){
printf " <TR bgcolor="#dfdfdf"> "
for( i=1; i<=NF; i++ )
{
printf " <TD><center>%s</center></TD> ", $i;
}
printf " </TR> "
}
(NF>0 && NR>1){
printf " <TR> "
for( i=1; i<=NF; i++ )
{
if ( i==1 ) {
printf " <TD align=left>%s</TD> ", $i;
} else {
printf " <TD align=right>%s</TD> ", $i;
}
}
printf " </TR> "
}
END {
printf "</TABLE> ";
}
$ awk -f array2html.awk table.txt > output.html
On execution of the previous code, a file named output.html will be created in the current directory. Open that file in the browser to view the HTML file content.