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但在这种情况下,会有大量无用的运行只是为了确定我是否找到了上一次运行的最后一行。我想知道我是否可以做得更有效率?

4

1 回答 1

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
于 2014-02-25T11:07:56.273 回答