Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to identify a date

Tags:

date

bash

I am trying to parse my /var/log/messages. I need a script that can verify the first 15 characters are a date. Every now and then, it contains a line like "---------------" which messes everything up.

A typical /var/log/message looks like:

Aug 12 13:22:33 xxxxxxx xxxxx xxxxx

My bash script looks to pull out the first 6 char and identify it as a date

if date -d "${line:0:3} ${line:4:2}" ; then 

This works fine and identifies the date, but if the line is a bunch of -----, it identifies it as a date too.

How can I just check if the line starts with a date?

like image 771
George Avatar asked Dec 25 '22 05:12

George


2 Answers

Check that the beginning of the line looks like a date:

line="Aug 12 13:22:33 xxxxxxx xxxxx xxxxx"
if [[ $line =~ ^([[:alpha:]]{3} +[[:digit:]]{1,2} [:[:digit:]]{8}) ]]; then 
    echo "${BASH_REMATCH[1]}"
fi
Aug 12 13:22:33
like image 149
glenn jackman Avatar answered Jan 05 '23 20:01

glenn jackman


You can check for line starting with ---- like this:

[[ "$line" != "----"* ]] && if date -d "${line:0:3} ${line:4:2}" ; then
like image 31
anubhava Avatar answered Jan 05 '23 18:01

anubhava