Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I would like to know how to convert a text file in UNIX to HTML using awk?
For example,
my file has the following contents :Name Age
A 23
B 16
C 60
D 29How to output as html as a table?
Thanks!
mm

Hi,
If I understand correctly, you want to convert a columnar textfile to an HTML table.
The code below will do that:
echo "Type name of file to be converted"
read infile
outfile=$infile.html
echo "<table border=1>" > $outfile
cat $infile|while read line
do
echo "<tr>" >> $infile.html
echo $line|awk -v newfile=$outfile '{
for(i=1;i<=NF;i++)
{
print("<td>" $i "</td>") >> newfile
}
}'
echo "</tr>" >> $outfile
done
echo "</table>" >> $outfileI am not sure if this site will let me post the html tags literally....I am giving it a try...
Anukta

Line no 7 should have been
echo "<tr>" >> $outfileThis is very basic HTML table, u might want to modify this to suit your requirement.
-Anukta

Hi,
I am basically making use of Anukta's code only but with a few changes, in way that i am avoiding the read of the file using cat command, rather i am using awk directly to interpret lines.Here it is:
#!/bin/ksh
read infile?'Type name of file to be converted: '
outfile=$infile.html
nawk -v newfile=$outfile 'BEGIN{\
print "" > newfile
}
{
print "" >> newfile
for(i=1;i" $i "") >> newfile
}
print "" >> newfile
}
END{print "" >> newfile }' $infileThe difference between the code will be noticeable if you input file is large, else remains the same.
One more thing i am using nawk instead of awk as some machines dont understand the -v option, due to the older version of awk.
~deeps

well, i should have known that .... :-)
Let's try again....
#!/bin/ksh
read infile?'Type name of file to be converted: '
outfile=$infile.html
nawk -v newfile=$outfile 'BEGIN{\
print "" > newfile
" >> newfile }' $infile
}
{
print "" >> newfile " >> newfile
for(i=1;i<=NF;i++)
{
print("" $i " ") >> newfile
}
print "
}
END{print "hope this works....
Someone should take Anukta's idea and change the code on this web page, as it gets too slow to give an answer with those signs :)
~deeps

well, i should have known that .... :-)
Let's try again....
#!/bin/ksh
read infile?'Type name of file to be converted: '
outfile=$infile.html
nawk -v newfile=$outfile 'BEGIN{\
print "<table border=1>" > newfile
}
{
print "<tr>" >> newfile
for(i=1;i<=NF;i++)
{
print("<td>" $i "</td>") >> newfile
}
print "</tr>" >> newfile
}
END{print "</table>" >> newfile }' $infilehope this works....
Someone should take Anukta's idea and change the code on this web page, as it gets too slow to give an answer with those signs :)
~deeps

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |