There are many cases in which we will need an HTML output for the reports we create using a shell script.
For example, if you create a file using a shell script that contains all the username and their ids from /etc/passwd file, you can convert it into an HTML file for more comprehensible output.
In this tutorial, I will explain how to convert the contents of a file to HTML format with proper table headers, rows, and columns data.
Shell Script to convert contents of a file to HTML Table:
This script converts and creates a new HTML format for the input file.
The below script uses “;” delimiter to parse the text file data. The explanation for running the script is given below the script.
You might like: 97% OFF on Udemy Shell Scripting Courses
Example input format
Your text file should have values with a delimiter as shown in the example below.
sam; newyork; 1345B; 78sdf3473;
msnam; newsdfyork; 1345B; 783473;
sadfm; newysdfork; 1345B; 7sdf83473;
sam; newysdfork; 1345B; 783sdf473;
sasdfm; newysdfork; 1345B; 7834sdf73;
If the delimiter is other than “;”, you can change the delimiter in “while IFS=’;’” to a different delimiter. For example, “while IFS=’-‘”
#! /bin/bash
if [ $# -eq 0 ] ; then
echo "USAGE: $(basename $0) file1 file2 file3 ..."
exit 1
fi
for file in $* ; do
html=$(echo $file | sed 's/\.txt$/\.html/i')
echo "<html>" >> $html
echo "<style type="text/css">
table, th, td {
border: 1px solid black;
}
</style>" >> $html
echo " <body>" >> $html
echo '<table>' >> $htm
echo '<th>HEADING1</th>' >> $html
echo '<th>HEADING2</th>' >> $html
echo '<th>HEADING3</th>' >> $html
echo '<th>HEADING4</th>' >> $html
while IFS=';' read -ra line ; do
echo "<tr>" >> $html
for i in "${line[@]}"; do
echo "<td>$i</td>" >> $html
# echo "<td>$i</td>" >> $html
done
echo "</tr>" >> $html
done < $file
echo '</table>'
echo " </body>" >> $html
echo "</html>" >> $html
done
Step 1: Save the above script in .sh format ( for example, convert.sh )
Step 2: Change the file permissions for execution using the following command.
sudo chmod +x convert.sh
Step 3: This script takes the text file as an argument. So when you run the script, pass the text file you want to convert as an argument as shown below.
sudo sh convert.sh file.txt
Step 4: Once you run the above command, the script will convert all your text data into a new HTML file name file.html
Step 5: If you want to convert files other that txt, change the txt format to your desired format in the for loop.
With Linux courses from Udemy, you can be confident that your skills will grow on the go.
There are many different ways for people to learn more about this efficient and versatile operating system so take advantage of what’s available today!