解析尾文件以处理命令

问题描述 投票:0回答:1

我找到了一些关于此的信息,但不足以让我继续这个项目。我的 bash 经验有限,正在努力学习。

我有一个日志文件,我想读取(尾部)并根据日志中的时间戳处理行。

日志示例:来自 tail -f filename.txt | grep --行缓冲 RXKEY,MAIN

20230913200618,12345,RXKEY,主

20230913200620,12345,RXKEY,主

20230913200627,12345,RXKEY,主

20230913200629,12345,RXKEY,主

(时间戳、ID、类型、位置)

如果最后一个条目比前一个条目早 X 秒,我想读取此文件并执行操作。 IE,如果 2 个日志在 4 或 5 秒内命中,则在本地运行命令。然后继续监控未来的日志并根据需要重复。

我的日志可以工作,但不确定如何读取时间戳,然后处理操作。

bash tail
1个回答
0
投票

您可以将

grep
传送到
while read
,这样您就可以循环接收到的每一行。

#!/usr/bin/env bash

declare allow_difference=5
declare last=

# 'while read -r' to prevent backslashes from being interpreted
# https://unix.stackexchange.com/questions/192786/what-is-the-meaning-of-read-r
tail -f filename.txt | grep --line-buffered RXKEY,MAIN | while read -r line; do
    # read into array 'linearray', splitting on ','
    # https://helpmanual.io/builtin/readarray/
    readarray -d , -t linearray <<<"$line"
    # [[ -z "$somevariable" ]] checks if the variable is empty
    # if its empty, then we havent set a last time yet, so set it and continue the while loop
    if [[ -z "$last" ]]; then
        last=${linearray[0]}
        continue
    fi
    # get the difference between the current time and the last time
    # $(()) for bash arithmetic
    difference=$((linearray[0] - last))
    # if the difference is smaller than the allowed difference, then run some command
    if ((difference < allow_difference)); then
        echo "difference between ${last} and ${linearray[0]} is ${difference}, running command"
        # could add some other command here...
    fi
done

尝试发表评论,因为您是新来的

bash
,但如果有些内容无法理解,请告诉我。

 $ ./script 
difference between 20230913200618 and 20230913200620 is 2, running command
^C
© www.soinside.com 2019 - 2024. All rights reserved.