0

我制作了一个 Bash 脚本来监视某些服务器日志文件中的某些数据,而我的方法可能不是最有效的。

有一个部分特别困扰我,我必须在受监控的日志中写一个换行符,这样同一行就不会被连续读取。

反馈将不胜感激!

#!/bin/bash

serverlog=/home/skay/NewWorld/server.log
onlinefile=/home/skay/website/log/online.log
offlinefile=/home/skay/website/log/offline.log
index=0

# Creating the file
if [ ! -f "$onlinefile" ]; then
    touch $onlinefile
    echo "Name                  Date            Time" >> "$onlinefile"
fi
if [ ! -f "$offlinefile" ]; then
    touch $offlinefile
    echo "Name                  Date            Time" >> "$offlinefile"
fi

# Functions
function readfile {

# Login Variables
loginplayer=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $4}'`
logintime=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $2}'`
logindate=`tail -1 $serverlog | grep "[INFO]" | grep "joined the game" | awk '{print $1}'`

# Logout Variables
logoutplayer=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $4}'`
logouttime=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $2}'`
logoutdate=`tail -1 $serverlog | grep "[INFO]" | grep "left the game" | awk '{print $1}'`

# Check for Player Login
    if [ ! -z "$loginplayer" ]; then
        echo "$loginplayer          $logindate  $logintime" >> "$onlinefile"
        echo "Player $loginplayer login detected" >> "$serverlog"
        line=`grep -rne "$loginplayer" $offlinefile | cut -d':' -f1`
        if [ "$line" > 1 ]; then
            sed -i "$line"d $offlinefile
            unset loginplayer
                    unset line
        fi
    fi
# Check for Player Logout
    if [ ! -z "$logoutplayer" ]; then
        echo "$logoutplayer         $logoutdate $logouttime" >> "$offlinefile"
        echo "Player $loginplayer logout detected" >> "$serverlog"
        line=`grep -rne "$logoutplayer" $onlinefile | cut -d':' -f1`
        if [ "$line" > 1 ]; then
            sed -i "$line"d $onlinefile
            unset logoutplayer
            unset line
        fi
    fi
}

# Loop
while [ $index -lt 100 ]; do
    readfile
done

谢谢!

4

1 回答 1

0

而不是使用多个

tail -n 1 file

尝试以下构造:

tail -f file | while read line;do
   echo "read: $line"
done

它会更加可靠......并且不会两次阅读同一行;)

注意:通过使用 grep/awk/etc 的新进程,你正在烧掉进程......这并不是说它很关键,但通常进程创建很昂贵......但如果很少出现新行,那很好

我想要得到的是:如果你有兴趣,看看 bash 构建字符串操纵器函数替换 $(x/aa} ${x//aa} 和朋友..或尝试使用扩展的正则表达式和 grep

于 2013-07-19T16:31:59.307 回答