如何解析文件中的日期,然后在bash中匹配日期之后插入一行?

时间:2014-05-13 00:48:33

标签: bash date

我的问题是我不知道如何阅读和解析日期,然后在该日期之后将一行添加到文件中。我有一个日志文件,并希望根据它们发生的时间添加重新启动。

日志文件看起来像这样,我上次重启是21:15 ..

[2014-05-12 20:49] upgraded something
[2014-05-12 20:49] upgraded something else
[2014-05-12 20:50] upgraded yet something else
[2014-05-12 21:51] upgraded something
[2014-05-12 21:51] upgraded other something
[2014-05-12 21:52] upgraded that something 

我希望它看起来像这样..

[2014-05-12 20:49] upgraded something
[2014-05-12 20:49] upgraded something else
[2014-05-12 20:50] upgraded yet something else
REBOOTED
[2014-05-12 21:51] upgraded something
[2014-05-12 21:51] upgraded other something
[2014-05-12 21:52] upgraded that something 

我的计划是使用who -blast reboot来获取重启的时间,但之后我不确定。过滤日期不是问题。我只是使用grep -o,但因为它不是一个确切的日期来匹配它变得困难。所以我猜我需要将who -b的输出发送到date,然后在日志文件中匹配。当找到最近的日期附加"重新启动"。

1 个答案:

答案 0 :(得分:1)

这是示例代码。 我假设您正在使用linux的GNU日期命令, 并且您的日志按时间顺序排序。

BOOT_TIMETMP2类似于2014-05-12 21:51

请参阅http://tldp.org/LDP/abs/html/string-manipulation.html ${VAR#}${VAR$}的含义

注意:如果没有用户登录,who -b似乎不起作用。 有关详细信息,请参阅以下URL: https://superuser.com/questions/263486/linux-getting-date-time-of-system-startup

#!/bin/bash
BOOT_TIME=$(date +"%F %H:%M" -d "$(cut -f1 -d. /proc/uptime) seconds ago")
REBOOT_FLAG=""
while read line;do
  TMP1=${line%]*}
  TMP2=${TMP1#[}
  if [ -z "$REBOOT_FLAG" ] && [ "$TMP2" \> "$BOOT_TIME" ];then
    echo REBOOTED
    REBOOT_FLAG="true"
  fi
 echo "$line"
done

一样使用它
$ ./this-script.sh < logfile