• Uncategorized

About linux : How-to-get-last-N-min-or-N-hour-logs-from-any-log-files-using-command-in-linux

Question Detail

I need to get the logs of the last n min or n hrs from any log file. I searched and executed many commands but none of them not working. If there is any specific command rather than script it would be perfect. my time format for Nginx is “2022/01/05 11:47:41”

I tried below commands

awk -v bt=$(date "+%s" -d "30 minutes ago") '$1 > bt {printf("%s|%s|%s\n", strftime("%F %T",$1), $3, $7)} ' /var/log/nginx/access.log

sed -n "/^$(date --date="60 minutes ago" "+%d/%b/%Y:%H:%M")/,\$p" /var/log/nginx/access.log

grep -E (date -d -15minutes "+%Y/%m/%d %H:%M"|date -d "+%Y/%m/%d %H:%M")

and many commands like above.

Question Answer

Try this command and it works for me

sed -n /$(date --date="15 minutes ago" "+%T")/,/$(date "+%T")/p logfile > newfile

date --date="15 minutes ago" "+%T" is time before 15 minutes

date "+%T" is the current time

You have to modify the time format based and your log file

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.