Unix Command to grep a time range

72,389

Try egrep:

pttrn="2014-12-04 0[0-9]"
pttrn="${pttrn}|2014-12-04 1[0-6]"
pttrn="${pttrn}|2014-12-04 17:00:00"

egrep "${pttrn}" <logfile>

The egrep pattern contains three parts. The first part grabs everything from 00:00:00 to 09:59:59. The second part grabs everything from 10:00:00 to 16:59:59, and the third part grabs 17:00:00.

Share:
72,389

Related videos on Youtube

uSlackr
Author by

uSlackr

IT Director by day, tech enthusiast, homebrewer, dad, husband, etc by night. Things I use: slackware,Linux, Windows, windows phone, VirtualBox, Tiki, AD, Subsonic, Amahi, Powershell, and more. Things I'm learning: iOS programming; PowerShell Find my tech blog [tiki.gmartin.org][1] [1]: http://tiki.gmartin.org

Updated on September 18, 2022

Comments

  • uSlackr
    uSlackr almost 2 years

    I have a log file, saved with particular date. I wanna fetch log entries during a particular time and date range to another file.

    Ex: all entries from 2014-12-04 00:00:00 time to 2014-12-04 17:00:00

  • wurtel
    wurtel over 9 years
    True; you could leave out the :00 part, but then again there would have to be at least one log line per hour. Personally I'd adapt the script to fit the data; perhaps even apply some perl foo.
  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' over 9 years
    Your first egrep eliminates values beginning with 08 or 09 (i.e., times between 08:00 and 09:59), and the second one allows 17:10, 17:20, 17:30, etc..., to get through.
  • Daniel Goldfarb
    Daniel Goldfarb over 9 years
    @G-Man Thanks. You're right. I think I've fixed it now.
  • G-Man Says 'Reinstate Monica'
    G-Man Says 'Reinstate Monica' over 9 years
    That looks like it should work. It could be simplified to egrep "2014-12-04 (0[0-9]|1[0-6]|17:00:00)".
  • Community
    Community over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.