I want to get all lines between two timestamps from /var/log/messages. I only have start time which I provide to my script as input. The script then should get me all the lines till next day as output. I tried this-

toDate=`date -d "${startDate}+1day"`
sed -n '/${startDate}/ , /${toDate}/p' messages* 

However I found a problem with this approach when the $toDate pattern is not found in message logs. So I modified my code to this-

toDate=`date -d "${startDate}+1day"`
until [ `grep -Fxq ${toDate} messages*` ];
    echo ${toDate}
    epoch=`date -d "${toDate}" +%s`
    next_ts=`date -d "1970-01-01 ${new_epoch} sec"`
sed -n '/${startDate}/ , /${toDate}/p' messages* 

Now I'm having a hard time matching date in the logs. For my input of Nov 6 07:17:04 UTC 2017, code generates next date as Nov 7 07:17:04. Notice that actual timestamps in message logs contains two spaces between month name and single digit dates. So I'm not not able to match the string.

Is there anyway around this? I want the script to work with double-digit dates(like 10) as well.

  • I never even knew until was a thing in bash. I am fairly certain though, that date has a man page which covers the topic FORMAT. – Bananguin Nov 10 '17 at 9:27
  • 2
    I would go for an awk on the form of awk '/initial date/,/final date/'. See How to filter logs easily with awk? – fedorqui Nov 10 '17 at 9:31
  • How about date +%a\ \ %d\ %T\ %Z (or the same thing quoted without the backslashes, which unfortunately is not displayed properly in a comment)? – dessert Nov 10 '17 at 9:37
  • If this a system running systemd, you can use journalctl --since and --until. – Raman Sailopal Nov 10 '17 at 9:46
  • @fedorqui Even with awk I see the same problem. If the final date is not found in logs, it print lines which which are not between range of timestamps too. – pragmatic Nov 10 '17 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.