fedora
July 19, 2006, 3:00pm
1
Hi all, I have tried to figure out a way to automatically get the last 5 minutes' log content from log file, at first, my thoughts like this,
sed -n "/ $(date +\%R -d "-5 min")/,$"p syslog > newfile,
but quickly I found it did not work, say I have a syslog file as following,
Jul 19 18:15:23 ........
Jul 19 18:15:28 ........
Jul 19 18:17:11 ........
Jul 19 18:18:11 ........
if the script run at 18:2118:21 minus 5minutes is 18:16since there is no "18:16" in logfile, sed will find no match, thus there will be nothing in the newfile", although actually it should have!
I know there will be solution around the corner, but how? Thanks!
reborg
July 19, 2006, 3:29pm
2
Well since there are only 5 minutes you are interested in:
in bash
for (( i = 5; i >=0; i-- )) ; do
grep $(date +%R -d "-$i min") syslog >> newfile
done
1 Like
fedora
July 19, 2006, 3:34pm
3
Hi reborg, thank you for your reply,
I am just wondering is there any other better solution other then using "grep",
If the syslog file is super large, doing loop and grep maybe not a very good solution. :rolleyes:
Hitori
July 19, 2006, 4:39pm
4
Try this one
#!/bin/sh
e=
for (( i = 5; i >= 0; i-- )) ; do
e='-e /'`date +\%R -d "-$i min"`'/p '$e
done
$(sed -n $e syslog > newfile)
This script generates commands like
sed -n -e /23:40/p -e /23:39/p -e /23:38/p -e /23:37/p -e /23:36/p -e /23:35/p syslog > newfile
reborg
July 19, 2006, 4:42pm
5
Well you could use egrep and multiple patterns to only search once.
assign each of the last 5 minutes to a variable and do
egrep "var1|var2|var3|var4|var5" syslog > newlog
or just take the last line of the previous extracted log.
var=$(tail -1 last_log_file)
sed -ne "/$var/"',$p' syslog > newlog
fedora
July 19, 2006, 4:49pm
6
AH! much better, thanks, you guys!