Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a log file, each line in the log is prepend with a date, like so:

2012-03-06 11:34:48,657 blah blah blah...

How do I grep this file and get only the lines from 8am to 11pm only?

My intention is I want to count the number of errors happening within 8am to 11pm.

share|improve this question
up vote 14 down vote accepted
egrep '^[^ ]+ (0[89]|1[0-9]|2[012]):'

Detailed explanation can be found in various regex (regular expression) tutorials; egrep uses "POSIX extended" syntax (man 7 regex).

  • The first ^ means "start of the line".

  • [^ ]+ just matches the date field, regardless of the actual date.

    • [...] means "any character between the brackets", so [89] will match either 8 or 9; [0-9] is any number, and [^ ] is anything except a space (because of the ^ inside brackets).

    • + means "one or more of the previous" (for example, a+ would match a, aaa, and aaaaaaaa).

    • So ^[^ ]+ will start with the beginning of line, and match as many non-space characters as it can.

  • (...|...|...) means "either of the given patterns", so (0[89]|1[0-9]|2[012]) means "either 0[89] or 1[0-9] or 2[012]". It will match all numbers from 08 to 22.

A somewhat better option is:

awk -F'[: ]' '$2 >= 8 && $2 <= 22 { print }'

The -F option splits every line into separate fields according to the [: ] regex (matching either : or a space), and the awk script checks the 2nd column (the hour).

share|improve this answer
Hi, it works.. but can you add a little explanation how it works? I dont get the ^[^ ]+ part.. – null Jun 21 '12 at 11:14

Why bother using grep? You can simply use sed.


sed -n '/Jun 17 13:39:54/ , /Jun 18 10:50:28/p' kern.log

This will print all the logs between June 17 13:39:54 and June 18 10:50:28

share|improve this answer
I think the OP wants all logs between 8am and 11pm, bot just the ones from a specific day. – Dennis Jun 21 '12 at 11:14
He can do that too. Eg: sed -n '/2012-3-06 11:34:48/,/2012-3-06 16:34:48/p' – Nima Jun 21 '12 at 11:16
Nasty typo. I meant: not the ones from a specific day. – Dennis Jun 21 '12 at 11:29
The problem with this approach is that there has to be a line in the log file with that timestamp. In the above example, if there is no line with timestamp 2012-03-06 11:34:48, then nothing will print out. The awk approach above would work for such cases (i.e. you want all logs with hour between 8 and 11, but you don't know if there is a log entry at time 2012-03-06 08:00:00 or anything for that hour at all). – user650654 Nov 19 '14 at 21:03

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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