首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >BASH监控文件的更好方法

BASH监控文件的更好方法
EN

Stack Overflow用户
提问于 2013-07-19 22:01:17
回答 1查看 1.1K关注 0票数 0

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

有一节让我特别头疼,那就是我必须在被监视的日志中写一个新行,这样同一行就不会被重复读取了。

我们将非常感谢您的反馈!

代码语言:javascript
运行
复制
#!/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

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2013-07-20 00:31:59

不是使用多个

代码语言:javascript
运行
复制
tail -n 1 file

尝试以下构造:

代码语言:javascript
运行
复制
tail -f file | while read line;do
   echo "read: $line"
done

这将是更多的reliable...and不会读取同一行两次;)

注意:通过使用grep/awk/etc的新进程,您正在烧毁进程……这并不是说这很关键,但通常进程创建是expensive...but的如果新行很少出现,这是非常好的

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17748057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档