天天看點

shell腳本利用gnuplot繪制圖檔

我們都知道gnuplot可以繪制圖檔,但是時候,我們的資料是以date檔案的形式存在,如何編寫一個腳本幫助我們繪制出相應的圖檔:

以某個程序的CPU使用情況為例:

catprocessX_CPU_Usage.log

WedOct1614:47:35CST2013:ProcessCPUsage(%)Total

WedOct1614:47:37CST2013:1828172008

WedOct1614:47:39CST2013:1828171706

WedOct1614:47:42CST2013:1828121689

WedOct1614:47:44CST2013:1828211673

WedOct1614:47:46CST2013:1828151668

WedOct1614:47:48CST2013:182881699

WedOct1614:47:50CST2013:1828171699

WedOct1614:47:53CST2013:1828172148

WedOct1614:47:55CST2013:1828151815

WedOct1614:47:57CST2013:1828321727

WedOct1614:47:59CST2013:1828111669

WedOct1614:48:01CST2013:182841667

WedOct1614:48:03CST2013:182881678

WedOct1614:48:05CST2013:1828161694

WedOct1614:48:08CST2013:182891669

WedOct1614:48:10CST2013:1828261750

WedOct1614:48:12CST2013:182861792

WedOct1614:48:14CST2013:1828141720

WedOct1614:48:17CST2013:1828121800

WedOct1614:48:19CST2013:1828241921

WedOct1614:48:21CST2013:1828111749

WedOct1614:48:23CST2013:182891708

WedOct1614:48:25CST2013:1828151665

WedOct1614:48:27CST2013:182831751

WedOct1614:48:30CST2013:1828101692

WedOct1614:48:32CST2013:1828151678

WedOct1614:48:34CST2013:1828191708

WedOct1614:48:36CST2013:1828141707

WedOct1614:48:38CST2013:1828151680

WedOct1614:48:40CST2013:1828181678

我們看到了輸出是這麼個情況,我們希望繪制一張簡單的圖檔,把CPUusage的情況繪制出來:每一行的第八列是我們想要的資料,我們可以繪制一個時間序列:

manu@manu-hacks:~/code/shell/gnuplot$catwork.sh

<code>#!/bin/sh</code>

<code>file</code><code>=$1</code>

<code>field=$2</code>

<code>yfield=`</code><code>cat</code> <code>$</code><code>file</code> <code>|</code><code>awk</code> <code>'{if(NR==1) print $'</code><code>''</code><code>$field</code><code>''</code><code>'}'</code><code>`</code>

<code>title=`</code><code>basename</code> <code>$</code><code>file</code><code>`</code>

<code>if</code> <code>[ $</code><code># -eq 2 ]</code>

<code>then</code>

<code>echo</code> <code>"</code>

<code>set</code> <code>terminal pngcairo lw 2</code>

<code>set</code> <code>title \"$title\"</code>

<code>set</code> <code>ylabel \"$yfield\"</code>

<code>set</code> <code>output </code><code>'./output/$title-$yfield.png'</code>

<code>plot \"$</code><code>file</code><code>\" using $field w lp pt 7 title \"$yfield\"</code>

<code>set</code> <code>output</code>

<code>set</code> <code>terminal wxt</code>

<code>" | gnuplot</code>

<code>fi</code>

我這個方法比較簡單,title就是資料來源的檔案名字,ylabel是字段名字,實際上,由使用者輸入titleylabel以及圖例的title會更加合适。我這隻是一個簡單的sample,來分享如何在shell腳本利用gnuplot繪制圖檔。

使用指令如下:

./work.sh/home/manu/processX_CPU_Usage.log8

輸出圖檔如下:

shell腳本利用gnuplot繪制圖檔

我這是一個簡單的例子,實際上,我們實際可能會跑出來40個程序的CPU使用情況,我們可以将參數寫入配置檔案,然後每一行去執行work.sh,這樣的話,我們就可以直接維護配置檔案就可以了。當然了,我的腳本還很簡陋很粗糙粗,遠遠不能在工程中實際使用。畢竟是晚上搗鼓出來的小玩意兒。

本文轉自大角牛部落格51CTO部落格,原文連結http://blog.51cto.com/jingshengsun888/1313918如需轉載請自行聯系原作者

運維的戲子