Home > Enterprise >  grep between timestamps from logs in Unix
grep between timestamps from logs in Unix

Time:08-24

I have the following logs

2022-07-23T09:00:00,987 hi
2022-07-23T10:00:00,987 hi
2022-07-23T11:10:00,987 hi
2022-07-23T12:52:00,987 hi
2022-07-23T13:29:00,987 hi
2022-07-23T13:59:00,987 hi

I want to grep only the lines between 10 AM to 13:30 PM. Here is my command, but it doesn't retrieve the result as expected. Any ideas where it has to fix

sudo cat <path to my log file> | grep 'hi' | grep -E '2022-07-23T(10:[0-5][0-9]:[0-5][0-9]|13:30:00)'

CodePudding user response:

awk is better tool for this than grep:

awk -F '[T,]' '$2 >= "10:00" && $2 <= "13:30" && /hi/' file

2022-07-23T10:00:00,987 hi
2022-07-23T11:10:00,987 hi
2022-07-23T12:52:00,987 hi
2022-07-23T13:29:00,987 hi

Here:

  • Using -F '[T,]' we delimit fields on T or , chars
  • awk -F '[T,]' '$2 >= "10:00" && $2 <= "13:30" does lexicological comparison of 2nd field with our data range
  • /hi/ search for hi in a line

Here is a grep solution using regex magic:

grep -E '^[^T] T1([0-2]|3:([0-2][0-9]|30)):.* hi' file

2022-07-23T10:00:00,987 hi
2022-07-23T11:10:00,987 hi
2022-07-23T12:52:00,987 hi
2022-07-23T13:29:00,987 hi

RegEx Demo

RegEx Details:

  • ^: Start
  • [^T] :
  • T1: Match T followed by digit 1
  • ([0-2]|3:([0-2][0-9]|30)): Match digits 0 to 2 to match time starting with 10 or 11 or 12. After alternation we match hour 13 followed by minutes 00 to 29 or 30
  • :.* hi: Match : followed by any string followed by a space and hi
  • Related