Creating an HTML table with BASH & AWK

2020-06-24 17:26发布

问题:

I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is:

(The comments in the following script show the outputs)

#!/bin/bash

function getapistats () {
    curl -s http://api.example.com/stats > api-stats.txt
    awk {'print $1'} api-stats.txt > api-stats-int.txt
    awk {'print $2'} api-stats.txt > api-stats-fqdm.txt
}

# api-stats.txt example
#    992 cdn.example.com
#    227 static.foo.com
#    225 imgcdn.bar.com
# end api-stats.txt example

function get_int () {

    for i in `cat api-stats-int.txt`;
        do echo -e "<tr><td>${i}</td>";
    done
}

function get_fqdn () {

    for f in `cat api-stats-fqdn.txt`;
        do echo -e "<td>${f}</td></tr>";
    done

}

function build_table () {

echo "<table>";
echo -e "`get_int`" "`get_fqdn`";
#echo -e "`get_fqdn`";
echo "</table>";
}

getapistats;

build_table > api-stats.html;

# Output fail :|
# <table>
# <tr><td>992</td>
# <tr><td>227</td>
# <tr><td>225</td><td>cdn.example.com</td></tr>
# <td>static.foo.com</td></tr>
# <td>imgcdn.bar.com</td></tr>

# Desired output:
# <tr><td>992</td><td>cdn.example.com</td></tr>
# ...