2014-02-25 105 views
0

我寫在bash簡單的腳本,來分析一些實時的日誌,不知道如何接近事實,每隔幾秒鐘我必須要找到文件到位我上次讀完了。 現在我做這樣的事情:實時日誌分析器 - 文件訪問每隔幾秒鐘

LOG_FILE=path_to_file 
DELAY=1 #time between refresh 
LINES=100 #lines to read at one cycle 

LAST=$(tail -n 1 $LOG_FILE)  

IFS=$'\n' 
while true; 
do 
    clear; 
    found=0 
    LOG=$(tail -n $LINES $LOG_FILE) 
    for line in $LOG 
    do 
     if [ $line = $LAST ]; then 
      found=1 
      continue 
     fi   
     if [ $found = 0 ]; then 
      continue 
     fi 
     #Analyzing counting nd stuff. 
     echo "$stuff" 
    done 
    LAST=$line 
    sleep $DELAY; 
done 

所以每次循環我取出由文件的末尾行的一些號碼和尋找一個這是最後在前面跑。這將工作得很好,直到在一個週期內,將添加更多定義的行數。我總是可以這樣說:LINES=10000但在這種情況下,將是無用的奔跑tousands只是爲了確定我還發現以前運行的最後一行。 我想知道我是否可以做得更高效?

+0

使用'尾-f' - 一個簡單的「等待另一個線」是不是一個解決方案? – jm666

+0

我想對數據做一些分析。每秒輸入的數量,一些avareges等等。我想也許從尾部捕獲輸出流可能是一個解決方案,但目前我在Bash上缺乏經驗來判斷它是否合理;)。 – Liberat0r

回答

1

我認爲你正在尋找某事像這樣:

#!/bin/bash 
GAP=10  #How long to wait 
LOGFILE=$1 #File to log to 

if [ "$#" -ne "1" ]; then 
    echo "USAGE: `basename $0` <file with absolute path>" 
    exit 1 
fi 


#Get current long of the file 
len=`wc -l $LOGFILE | awk '{ print $1 }'` 
echo "Current size is $len lines." 

while : 
do 
    if [ -N $LOGFILE ]; then 
     echo "`date`: New Entries in $LOGFILE: " 
     newlen=`wc -l $LOGFILE | awk ' { print $1 }'` 
     newlines=`expr $newlen - $len` 
     tail -$newlines $LOGFILE 
     len=$newlen 
    fi 
sleep $GAP 
done 
exit 0 
+0

這正是我所期待的。謝謝。 – Liberat0r

+0

歡迎您:) – MLSC

相關問題