How can I parse a date from file then insert a line after that matched date in bash?

StackOverflow https://stackoverflow.com/questions/23621170

  •  21-07-2023
  •  | 
  •  

My problem is that I am not sure how to read and parse a date and then append a line after that date to a file. I have a log file and want to add reboots according to when they have happened.

The log file looks like this and my last reboot was 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 

I want it to look something like this..

[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 

My plan is to use who -b or last reboot to get the times when the reboots occurred but after that I am not sure. Filtering out the dates are no issue. I'll just use grep -o but as it's not an exact date to match it becomes difficult. So I am guessing I need to send the output from who -b to date and then match for that in the log file. When closest date found append "REBOOTED".

有帮助吗?

解决方案

here's the sample code. I assume that you are working on linux's GNU date command, and your log is sorted in time order.

BOOT_TIME and TMP2 would be something like 2014-05-12 21:51.

see http://tldp.org/LDP/abs/html/string-manipulation.html what ${VAR#} and ${VAR$} means

NOTE: who -b does not seem to work if there is no user login'ed . see the following URL for more details: 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

use it like

$ ./this-script.sh < logfile
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top