3

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>
# ...
1
  • The single quotes go outside the curly braces. I know it works like that, but at the next simple increment in complexity it fails. Don't use for i in $(cat) - use while read -r; do ...; done < filename. Use $() instead of backticks. Commented Jul 14, 2012 at 20:27

3 Answers 3

11

This is reasonably simple to do in pure awk:

curl -s http://api.example.com/stats > api-stats.txt
awk 'BEGIN { print "<table>" }
     { print "<tr><td>" $1 "</td><td>" $2 "</td></tr>" }
     END   { print "</table>" }' api-stats.txt > api-stats.html

Awk is really made for this type of use.

Sign up to request clarification or add additional context in comments.

2 Comments

You can pipe the output of this directly to a browser using bcat or this little script on OSX
Shouldn't the last <tr> be `<\tr>' instead?
6

You can do it with one awk at least.

curl -s http://api.example.com/stats | awk '
    BEGIN{print "<table>"} 
    {printf("<tr><td>%d</td><td>%s</td></tr>\n",$1,$2)}
    END{print "</table>"}
' 

Comments

0

this can be done w/ bash ;)

    while read -u 3 a && read -u 4 b;do
      echo $a$b;
    done 3</etc/passwd 4</etc/services

but my experience is that usually it's a bad thing to do things like this in bash/awk/etc

the feature i used in the code is deeply burried in the bash manual page...

i would recommend to use some real language for this kind of data processing for example: (ruby or python) because they are more flexible/readable/maintainable

1 Comment

yeah python might be the way to. Thanks bud ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.