LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Show logs within a certain period of time (https://www.linuxquestions.org/questions/linux-newbie-8/show-logs-within-a-certain-period-of-time-4175603621/)

vincix 04-11-2017 04:13 AM

Show logs within a certain period of time
 
I tried using the following:
sed -n '/Apr 10/,/Apr 12/p' /var/log/cron | awk -F: '$1 >= 20 && $2 >= 50 { print }'

Sed displays all lines beginning with the first record from April 10 to the last record of April 11 (don't know exactly how to achieve this, so I wrote "Apr 12", which is tomorrow - I guess I can cut the last line when logs on April 12 will be populated).

The problem is that awk, for some reason, doesn't display all the hours starting with the 20th. It actually displays all hours, from 0 to 23. The weird thing is that the minute works, so $2 >= 50 does display only lines recorded after (and including) the 50th minute. Any idea why it does that?

Thanks

Turbocapitalist 04-11-2017 04:31 AM

Yes, you are using a colon as the field separator, so the fields are not numbers. You'll want to stick with white space as a field separator and then attack the time manually using split() or similar and then examine the pieces of the resulting array.

Or you could use a pattern for FS and include both white space and a colon in that pattern. You'll have to recalculate which fields to look at then.

syg00 04-11-2017 04:41 AM

Usually a good idea to print what you are testing when things go wrong - just so you know.

vincix 04-11-2017 04:44 AM

@Turbocapitalist. Yes, it's obvious now that the first field is going to be "MM DD HH:MM:SS". I completely missed that.

@syg00 By printing, you mean show others what is displayed on the screen?

syg00 04-11-2017 04:49 AM

Yep - basic debugging would be to print $1 and $2. Take it out when you get things fixed.

Shadow_7 04-11-2017 07:29 AM

Some log files store the date as the epoch date. If you want to fine tune your range to the minute or second, you might want to convert to epoch date. Otherwise the programmatic logic for the edge cases can get complex. You can use date to do most of that conversion. Although easier said than done as a lot of the comparisons are ascii strings, not numerical.

vincix 04-13-2017 09:55 AM

awk -F '[ :]' '$4 >= 2 && $5 >= 40 {print}' seems to work fine :)
Together with sed it behaves differently. For some reason, sed deletes one space between the month and the day (e.g. "Apr" and "10"), so I need to use awk but with columns $3 and $4 instead of $4 and $5, which would work if I start processing with awk.


All times are GMT -5. The time now is 02:05 AM.