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


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.

  • 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. Dec 11 '14 at 0:38
  • @G-Man Thanks. You're right. I think I've fixed it now. Dec 18 '14 at 3:56
  • That looks like it should work. It could be simplified to egrep "2014-12-04 (0[0-9]|1[0-6]|17:00:00)". Dec 18 '14 at 4:04

If you want 4 minutes interval of logs,

grep "01/APR/2014:16:3[5-9]" logfile

will return all logs lines between 16:35 and 16:39 on 01/Apr/2014.

Suppose you need the last 5 days starting from 17/Sep/2014 you may use the following:

grep "1[3-7]/Sep/2011" logfile

Hopes this helps,


You can select a starting line and an ending line with e.g. sed:

sed -n '/Dec  5 11:00/,/Dec  5 12:00/p' /var/log/daemon.log

This will print all lines from the first line with Dec 5 11:00 up to (and including) the first line with Dec 5 12:00. This is assuming the log is time-sequential (i.e. all lines are in order of time). The -n is to suppress the default action of printing each line.

  • But this assumes that there are entries for Dec 5 11:00 and Dec 5 12:00, doesn't it? If Dec 5 10:59 is immediately followed by Dec 5 11:01, then sed won't know where to start. And if there is a Dec 5 11:00, but then Dec 5 11:59 is followed by Dec 5 12:01, sed won't know where to stop. Dec 5 '14 at 21:53
  • 1
    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.
    – wurtel
    Dec 8 '14 at 9:00

In addition to above modifications in date range, one can search for intended strings in the same command line.


grep "Nov 30 18:" /var/log/maillog | grep "Remote_" | wc -l

Try increasing the search loops with adding more | or save the results in a file:

grep "1[3-7]/Sep/2011" /var/log/maillog > /var/krishna.txt
grep "1[3-7]/Sep/2011" /var/log/maillog > /tmp/results.txt

*wc -l counts the total in list generated from previous parts of the code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.