2014-02-25 43 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