1

I am having a log file where I need to grep based on yesterday date. How to get the yesterday date.

The time stamp in the log file is formatted as:

  • Wed Sep 23 for two digit
  • Wed Dec 1 for one digit

Note that I'm on HP/UX where date is not GNU date.

2 Answers 2

2

Hope you could use perl

$ dt=`perl -e 'print substr(scalar localtime(time-86400),0,10)'`
$ echo "$dt"
Sat Dec  5
$ grep "$dt" <logfile>

In the perl code above, time returns the current time in seconds since epoch. To get yesterday, subtracting 86400 seconds and scalar prints it in human readable format. I assume you just need yesterday in DAY MON DT format, so you could grep all lines matching that day, irrespective of time. To just grab required fields, using substr to print the first 10 characters and saving in dt variable. You could use that variable with grep.

3
  • 2
    Note that in timezones that do daylight-saving, there's one hour every year during which that doesn't work properly. Dec 6, 2015 at 22:48
  • I don't want to use perl . is their any another alternative
    – Pooja
    Dec 7, 2015 at 4:15
  • @Pooja Is C an option? will you be able to compile small piece of code to print yesterday (or) Does your awk support systime and strftime ? if so you could try echo | awk '{print strftime("%a %b %e",systime()-86400);}'
    – VenkatC
    Dec 7, 2015 at 14:38
0

Your question is poorly worded, but from what I gathered you're looking for something like this:

date --date="-1 day" +"%a %b %-d"

This will give you yesterdays date formatted in the same way you gave in your log file snippet. You can save this to a variable by doing:

yesterday=$(date --date="-1 day" +"%a %b %-d")

or to grep you can do something like the following:

yesterday=$(date --date="-1 day" +"%a %b %-d") ; grep "$yesterday" <file name>

I hope that answers your question

3
  • 1
    it doesn't support . I don't have gnu . I am using HP-UX. It's showing illegal options
    – Pooja
    Dec 6, 2015 at 18:47
  • Ah sorry, I don't know HP-UX or have a system of it to test on. You'll want to take a look at the man page for date on your system and try to replicate my solution or a similar one, its likely it will be a similar process just different flags are used etc
    – bevreti
    Dec 6, 2015 at 19:16
  • It does not allow to take as -1 day . I also tried but it didn't work @bevreti
    – Pooja
    Dec 6, 2015 at 19:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .