user6690412 user6690412 - 1 year ago 150
Bash Question

How to convert text file data into html table format in linux shell scripting

I want to convert samplefile.txt into html table format.It should ignore all special characters.The start of char

must go into table header,while the contents inside table header into table cell.

Also I want to format table heading and table border in this script.

This is a simple samplefile.txt:

Y|beach volleyball|boxing|diving
$|United States|United Kingdom|India

This is the script I have been working in - Somehow this code is not working 100%:

echo "<html>"
echo "<body>"
while read line
#echo $line
heading=`echo $line | cut -c-3`
headdata=`echo $line | cut -c4-`
if [ "$heading" == "###" ]; then
#if [ $tableflag -eq 1 ]; then
#echo "</table>"
echo "<th colspan="3" style="font-family: 'Times New Roman';"> $headdata </th>"
echo '<tr> </tr>'
echo '<table border="1" style="width:80%;margin:30px">'
echo '<tr>'
echo "$line" | awk -F"|" '{print "<td>" $2 "</td><td>" $3"</td><td>"$4"</td>"}'
echo '</tr>'
echo '<tr> </tr>'

done < samplefile.txt
echo "</table>"
echo "</body>"
echo "</html>"

Answer Source

There seems to be few issues with the script

1) echo "<th colspan="3" style="font-family: 'Times New Roman';"> $headdata </th>"

Here you have not escaped ". Correct syntax would be

echo "<th colspan=\"3\" style=\"font-family: 'Times New Roman';\"> $headdata </th>"

2) You are using backticks(`) to run a command.They are deprecated

heading=echo $line | cut -c-3

Instead use $()

heading=$(echo $line | cut -c-3)

3) I am assuming that you have print all four column in content when you split by |. But here you are printing only three column using awk

awk -F"|" '{print "<td>" $1 "</td><td>" $2"</td><td>"$3"</td>"}'

I suggest, if you do intent to print all four column, set the colspan to 4 instead of three

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download