THE COMPTGUY
THE COMPTGUY

Reputation: 33

How to find data between range of time using grep?

I am a new bash script student. I am learning about grep! I have a file that contains information about computer or activity. I am trying to use grep command to find information about my computer during a specific time range. I have tried following commands, but some work and some don't:

grep -E "Jan 09 22:00:00 && Jan 09 22:05:00" /etc/active #doesn't work
grep -E "Jan 09 22:00:00" && "Jan 09 22:05:00" /etc/active #doesn't work

Then I tried pipe

grep -E "Jan 09 22:00:00" | grep -E "Jan 09 22:05:00" /etc/active #doesn't work

If I try grep -E "Jan 09 22:00" /etc/active this work, but it is only one time. I want between two different times

I know there is a command awk, but we haven't started with awk!

Upvotes: 1

Views: 4119

Answers (1)

GhostCat
GhostCat

Reputation: 140573

I think what you are asking for simply doesn't work too good with grep. You see, grep is about matching text against patterns.

grep has no understanding of "dates"; or the semantics of dates. grep doesn't understand that "Jan 09 22:00:00" denotes a point in time; and that you are looking for the entries up to the next 5 minutes.

The only thing that you can do: use a pattern that matches that input.

For example: the pattern

 Jan 09 22:0.:..

should match any timestamp from 22.00.00 to 22.09.59

In other words: you can study how to create more sophisticated patterns (see here for some ideas); and then try to find patterns that match exactly what you need. But please understand that this might be hard, depending on your requirements.

Coming back to my intial point: grep is a tool to do "stupid" text matching. You are looking for something that works on a "higher level of abstraction".

EDIT: I actually really told you what you need to know, but maybe you need an example. So I cretead a file forgrep and put this in

Jan 09 22:00:00 zero
Jan 09 22:01:00 one
Jan 09 22:02:00 two
Jan 09 22:03:00 three

See what is possible using different regular expressions:

grep -E "Jan 09 22:01:00" forgrep 
Jan 09 22:01:00 one

The above matches the exact string provided, but

grep -E "Jan 09 22:0.:00" forgrep 
Jan 09 22:00:00 zero
Jan 09 22:01:00 one
Jan 09 22:02:00 two
Jan 09 22:03:00 three

simply matches any number there (because of the .)

grep -E "Jan 09 22:0[12]:00" forgrep 
Jan 09 22:01:00 one
Jan 09 22:02:00 two

matches numbers 1 and 2 in that place!

It doesn't get "better than that". You simply have study the link I provided to you and start making experiments.

As you can see: you can use patterns to

Upvotes: 1

Related Questions