0

I am trying to grep logs that happened in the last hour, time format is like this: 2020-11-01 18:46:56.036

I tried to run this:

grep "^$(date -d -1 hour +'%Y-%m-%d %H')" postgresql-Mon.log | tail -n 100

but that doesn't work. Also how do I use the tail command without -n? I want to grep from bottom to top but to get all the logs from the last hour not only 100.

Help please :>

I know there are other ways doing it but I need it with grep command

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
dddd4
  • 21
  • 1
  • 3

2 Answers2

1
grep "$(date "+%Y-%m-%d %H" -d '1 hour ago')"

must work

[root@dell-shatov-dk ~]# cat ./test.log 
2020-11-02 07:21:10.104 t1
2020-11-02 08:21:10.104 t2
2020-11-02 09:21:10.104 t3
2020-11-02 10:21:10.104 t4
2020-11-02 11:21:10.104 t5
[root@dell-shatov-dk ~]# grep "$(date "+%Y-%m-%d %H" -d '1 hour ago')" test.log
2020-11-02 11:21:10.104 t5
  • `[root@pg67 log]# cat test.log 2020-11-02 07:21:10.104 2020-11-02 08:21:10.104 2020-11-02 09:21:10.104 2020-11-02 10:21:10.104 You have new mail in /var/spool/mail/root [root@pg67 log]# grep $(date "+%Y-%m-%d %H" -d '1 hour ago') test.log grep: 07: No such file or directory test.log:2020-11-02 07:21:10.104 test.log:2020-11-02 08:21:10.104 test.log:2020-11-02 09:21:10.104 test.log:2020-11-02 10:21:10.104 [root@pg67 log]# date Mon Nov 2 08:55:02 UTC 2020 ` – dddd4 Nov 02 '20 at 08:59
  • `grep "$(date "+%Y-%m-%d %H" -d '1 hour ago')" test.log`, sorry, missing quotes – Дмитрий Шатов Nov 02 '20 at 09:15
  • This will fail if the grepped date is not in the file. – kvantour Nov 02 '20 at 09:23
0
grep "$(date "+%Y-%m-%d %H" -d '1 hour ago')" test.log
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
user3188140
  • 265
  • 1
  • 5