题
我正在 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
但在这种情况下,将会有数以千计的无用运行只是为了确定我是否找到了上次运行的最后一行。我想知道我是否可以做得更有效率?
解决方案
我认为你正在寻找这样的东西:
#!/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
不隶属于 StackOverflow