Linux Shell Script + AWStats 列出 MT Blog 文章點閱排行
AWStats 統計報表雖然可以查詢依存取次數排序的 URL, 但也僅止於 URL, 還要點進去看才知道是哪篇文章, 真的很不方便. 在 MovableType 官方網頁, 也只找到 AWStatsReferers 這個跟 AWStats 有關的 Plug-in, 可惜它只做到列出 PageRefer 的功能…
那就自己寫囉~ Perl? 沒信心; PHP? 系統慢, 效能差… 不然用 Shell Script 吧! 順便練習一下語法 :)
環境說明: 裝有 AWStats 統計套件的 Linux 環境
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#!/bin/sh awstats_file="/var/lib/awstats/awstats`date +%m%Y`.your.domain.name.txt" temp_file="/tmp/temp" output_file="/tmp/awstats`date +%m%Y`.tophits" cat $awstats_file | \ grep -A `grep "BEGIN_SIDER " $awstats_file | cut -d " " -f 2` "BEGIN_SIDER " | \ grep "/blog/archives" | \ grep ".html" | \ cut -d " " -f 1,2 | \ sort -k 2 -n -r > $temp_file echo "<table><tr style='color:yellow'><td>文章標題</td> <td align='right'>點閱次數</td></tr>" > $output_file for item in `cat $temp_file | cut -d " " -f 1` do if [ -e /var/www/html$item ]; then title=`cat /var/www/html$item | grep "dc:title" | head -n 1 | cut -d \" -f 2` url=`grep $item $temp_file | cut -d " " -f 1` hits=`grep $item $temp_file | cut -d " " -f 2` echo "<tr><td><a href='$url'>$title</a></td> <td align='right'>$hits</td></tr>" >> $output_file fi done echo "</table>" >> $output_file |
說明:
| 行號 | 說明 |
| 03 | AWStats 預設統計檔案路徑為: /var/lib/awstats, 檔名格式為: awstats052005.your.domain.name.txt, 其中 052005 為月、年. 指令備忘: date +%m%Y → 052005 (執行 date –help 可查詢所有格式參數) |
| 08 | 於統計檔案中, 找到 “BEGIN_SIDER ” 這個字眼 (最後要空一格, 以區別另一個統計區塊: “BEGIN_SIDER_404″), 並從該行開始往下抓 n 筆資料. 以上列程式來說, n 是統計檔案裡, “BEGIN_SIDER ” 旁邊那個數字, 表示全部抓出. 指令備忘: grep -A n “string_to_find” → 找到 “string_to_find” 後, 自該列起往下列出 n 列資料 cut -d “分隔字元” -f 第 n 欄位 → 若不加上 -d 參數, 表示以 Tab 分隔 |
| 09~10 | 只過濾出 Blog 文章的統計資料 (MovableType 文章預設儲存路徑為: $BlogRoot/archives/年/月/文章.html) |
| 11 | 只抓出前兩個欄位 (URL、Hits) → AWStats 統計檔案中有欄位說明 |
| 12 | 依第二個欄位 (Hits) 由大到小排序, 並將結果儲存到 $temp_file 檔案中 指令備忘: sort -k 欄位 -n -r → -k 指定排序依據欄位; -n 以數字方式進行比較; -r 降冪排列 (由大到小) |
| 14 | 從 $temp_file 檔案讀出第一欄的資料 (URL) |
| 16 | 判斷檔案是否存在 指令備忘: 請參閱 study-area.org 的 Shell 和 Shell Script, 可找到 if 的相關參數. |
| 17 | 從檔案取出文章標題 (在文章檔案的 dc:title=”xxx” 描述中) |
| 20 | 將文章標題、連結路徑和點閱次數組合成 HTML 語言, 並輸出到 $output_file |
完成後, 排程這個 Shell Script, 並在 PHP 網頁中 include $output_file 即可, 也可加以改寫, 在 Shell Script 中構築完整的 HTML 輸出.
順帶一提, 用 vim 編輯 UTF-8 含有中文內容的檔案時, 真的很不方便, 有時候動一下畫面就全亂了, 如果能自動轉碼就很理想喔:
#!/bin/sh if [ -z "$1" ]; then echo "Usage: edit <file_name>" elif [ -f "$1" ]; then cat "$1" | iconv -f utf8 -t big5 > ".$1" vim ".$1" cat ".$1" | iconv -f big5 -t utf8 > "$1" rm -f ".$1" else echo "$1 file not exist" fi
没有评论▼