how to filter with grep for hours?

by ortiga   Last Updated October 17, 2018 18:00 PM

I have the following log file, I want to cut the file with a grep but I only list the content that occurs from hours 7 to 19.

 Oct 11 05:26:56 cuervo sshd[983]: Server listening on :: port 22.
 Oct 11 06:26:56 cuervo sshd[983]: Server listening on :: port 22.
 Oct 11 07:26:56 cuervo sshd[983]: Server listening on :: port 22.
 Oct 11 08:26:56 cuervo sshd[983]: Server listening on :: port 22.
 Oct 11 09:26:56 cuervo sshd[983]: Server listening on :: port 22.
 Oct 11 19:40:38 cuervo polkitd[623]: Loading rules from directory
 Oct 11 20:40:38 cuervo polkitd[623]: Loading rules from directory        


Answers 1


You could use regex - play here:

grep -E '^ [^ ]+ [0-9]+ (0[7-9]|1[0-9])'

This will match any month, any date, and hours 07 - 19... numeric matching like this is not ideal in grep... because regex isn't great a numeric comparisons...


You could use awk:

awk '{split($3,x,":"); if ((x[1] >= 7) && (x[1] <= 19)){ print }}'
  • Split the 3rd field (i.e: the time) by colons (:), and store in the array named x
  • Print the line only if the first element of x (hours) is between 7 and 19
Attie
Attie
October 17, 2018 17:58 PM

Related Questions



Why does backup script fail with cron?

Updated February 20, 2017 17:00 PM

BASH - sed replace IP variants

Updated March 03, 2017 04:00 AM

Bash script odditiy

Updated September 06, 2017 22:00 PM

How to query custom installed rpm package

Updated October 23, 2018 21:00 PM