0

I want filter a file, and delete (or write to another file), only strings which Date are "realy" smaller then Date now, lets say for 2 hours 30 minutes ago (150 minutes). I don't need command which can find something like absolute value "2017-03-21 04:36:19" - and then delete all lines before. Because it`s a big chance that lines is not exist (seconds, then minutes, and this filter give all the file without deleting).

I have data in next format:

2017-03-18 01:27:12 bla bla
2017-03-18 02:14:11 bla bla
2017-03-20 04:37:14 bla bla
2017-03-21 02:25:59 bla bla
2017-03-22 05:12:43 bla bla

Time format: %Y-%m-%d %H:%M:%S

I search on google, and try everything on first page by many search queries.

Amaroc
  • 179
  • 1
  • 2
  • 9
  • 3
    See: [Find entries in log file within timespan eg. the last hour](http://stackoverflow.com/q/7706095/3776858) – Cyrus Mar 27 '17 at 04:49
  • What's the problem? You are using a sane date format, so you can simply use string comparison. – Michael Vehrs Mar 27 '17 at 06:01
  • *smaller then Date now, lets say for 2 hours 30 minutes ago (150 minutes)* - ok, today is `2017-03-27`. They are all smaller – RomanPerekhrest Mar 27 '17 at 07:08
  • @MichaelVehrs i realy trying to use these commands, exact from this post wich are you give me, but it dosn't work for me. Your answer exactly do what i need. – Amaroc Mar 27 '17 at 13:10

2 Answers2

2
awk -vdate=$(date -d "150 minutes ago" '+%Y-%m-%d%H:%M:%S') \
    '$1$2 >= date { print }' log
Michael Vehrs
  • 3,293
  • 11
  • 10
  • OMG, are you genius, i use same "commands" withe same syntaxis, but it never works. Thank you very much! – Amaroc Mar 27 '17 at 13:01
1

In awk:

awk '
BEGIN{ now=systime() }     # now in seconds 
{
    then=$1 " " $2         # then might not be a good var name though :)
    gsub(/[-:]/," ",then)  # making mktime fit variable out of then
    then=mktime(then)      # then then to seconds
    if(then < now-604800)  # compare, 604800 is 7 days in seconds
        print              # output older than that
}' file
2017-03-18 01:27:12 bla bla
2017-03-18 02:14:11 bla bla
2017-03-20 04:37:14 bla bla
James Brown
  • 36,089
  • 7
  • 43
  • 59
  • Thank you! Its works too (not for my goal). Its give me older then 7 days. Thats nice too. Maybe exist "inverse" option for awk, as in 'sed', so it can give just 7 days, or 150 minutes. – Amaroc Mar 27 '17 at 13:07
  • @Amaroc Just change the 604800 in the code to which ever time you want (in seconds), I had to use such value since your data was such. If you want only newer than 150 minutes: `if(then > now-9000)`. – James Brown Mar 27 '17 at 13:31
  • Thank you for help again, i will use this one (this one simple for read): awk -vdate=$(date -d "150 minutes ago" '+%Y-%m-%d%H:%M:%S') \ '$1$2 >= date { print }' log But yours method is also good and as i see it can parse another date format [-:]/," " so its cute! – Amaroc Mar 27 '17 at 13:39