user6690412 user6690412 - 3 months ago 29
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:

###File1
###File2
###File3
###Sports
Y|Cricket|Football|basketball
Y|beach volleyball|boxing|diving
Y|cycling|Batminton|Swimming
###Country
$|United States|United Kingdom|India
$|Peru|Japan|Poland


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

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

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

Answer

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

Comments