0

I am so beginner with linux .

    Oct 07  11:00:33 some text
    Oct 07  12:00:33 some text
    Oct 08  14:00:33 some text
    Oct 08  21:00:33 some text
    Oct 09  21:00:33 some text

I would like to grep logs between 2015-07-08 12:00:33 to 2015-07-10 21:00:31

I think I can do that with these codes that I've got from here ,

sudo awk -v start='2015-07-08 12:00:33' -v end='2015-07-10 21:00:31' '
 BEGIN{ gsub(/[:-]/," ", start); gsub(/[:-]/," ", end) }
      { dt=$1" "$2; gsub(/[:-]/," ", dt) }
 mktime(dt)>=mktime(start) && mktime(dt)<=mktime(end)' a.txt

I've tested it and it works perfectly when log date time format is 2015-10-09 21:00:33

but my log date time format is Oct 09 21:00:33

so I don't know How to convert it to 2015-10-09 21:00:33

2
  • 2
    There's a lesson: whatever writes to your logs, configure it to use a format like 2015-10-29 21:00:33, because timestamps in such format can be parsed, sorted or compared relatively easily. It doesn't have to be this exact format. The point is some formats are better than others when it comes to parsing, sorting or comparing; use this fact. I know this comment won't solve your current problem, but it may help avoid future ones. Commented Oct 16, 2022 at 8:34
  • 1
    I always prefer storing time in epoch seconds for this reason. Whatever you want you just convert to epoch second. Then back. At that the check you want is just a comparison of two integers.
    – john-jones
    Commented Oct 16, 2022 at 8:54

1 Answer 1

1

Since your logged timestamps is not easily parseable, so you will need to convert it to some parseable and also acceptable format to the mktime() function which is YYYY MM DD HH MM SS and since you having missing YYYY part so for that we added a dummy year as "2022" in the following code.

There is also a user-defined month2num() function which it converts the Months name into thier corresponding month-number.

gawk -v year='2022'  -v start='2022 10 07 12 00 33' -v end='2022 10 08 21 00 31' '
function month2num(mon ){
     return sprintf("%02d", (index("JanFebMarAprMayJunJulAugSepOctNovDec", mon)+2)/3)
 }

{ dt=year" "month2num($1)" "$2" "$3; gsub(/[:-]/," ", dt) }

mktime(dt)>=mktime(start) && mktime(dt)<=mktime(end)' infile

Output:

    Oct 07  12:00:33 some text
    Oct 08  14:00:33 some text

You must log in to answer this question.

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