2012-07-14 80 views
2

我在創建html表格以顯示文本文件中的統計信息時遇到問題。我相信,有100種方法可以做到更好,但在這裏它是:使用BASH&AWK創建HTML表格

(中下面的腳本註釋顯示輸出)

#!/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> 
# ... 
+0

單引號超出花括號。我知道它是這樣工作的,但是在下一個簡單的複雜性增量中,它就會失敗。不要在$(cat)中使用'for i' - 使用'while read -r;做...;完成 2012-07-14 20:27:02

回答

8

在純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確實是用於這種類型的應用。

+0

完美謝謝! – jdorfman 2012-07-16 20:36:27

+0

您可以使用[bcat](https://rtomayko.github.io/bcat/)或[這個小腳本](https://gist.github.com/HeinrichHartmann/5ab1a4396e264f507e78333c210e9c1c)將輸出直接傳輸到瀏覽器)on OSX – 2016-09-23 10:05:52

+1

不應該最後一個''是'<\tr>'而不是? – 2018-02-04 04:18:30

0

可以做到這一點W/bash的;)

 

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

但我的經驗是,它通常是一件壞事在bash做這樣的事情/ AWK /等

我在代碼中使用該功能深深在bash的手冊頁安葬......

我會建議使用一些真正的語言對這種數據的處理,例如:(Ruby或Python),因爲它們更靈活/可讀/可維護

+0

耶'python'可能是通向。謝謝芽;) – jdorfman 2012-07-14 19:52:24

3

至少可以用一個awk來完成。

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>"} 
' 
+0

也很有魅力 – jdorfman 2012-07-16 20:36:41