Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to find a date in a log file and print from that date till the end of log file and that date is 5 days prior to the end of log file which is 27/Dec/2002

the log file is like this : - - [01/Jan/2003:05:42:53 +0100]

the whole script :

for d in \
 $(sed -nre 's/.*\[(..)\/(...)\/(....):(..:..:..) .*/\1 \2 \3 \4/p' thttpd.log $
do echo $d >s1; done

time=$(expr 60 \* 60 \* 24 \* 5)
EDATE=`tail -1 s1`
SDATE=$[$EDATE - $time]
sd=`date -d '1970-01-01 UTC '$SDATE' seconds' +"%d/%b/%Y"`
sd=$(echo $sd | sed 's/\//\\\//g')
sed -n "$(awk '/'$sd'/ { print NR }' thttpd.log | head -1),$ p" thttpd.log

the problem is the date 27/Dec/2002 is not in log file ! so now how should i write to go for searching the next day (28/Dec/2002) - - [23/Dec/2002:03:02:22 +0100] - - [28/Dec/2002:19:33:29 +0100]

I also have this problem with hour too ! I want to print the last 5 hour which would be 07:55:21 , but there is not 7:55 in the log file ! so it should print from the next item till (08:08) the end - - [01/Jan/2003:07:53:17 +0100] - - [01/Jan/2003:08:08:19 +0100]
share|improve this question
up vote 2 down vote accepted

Didn't you solve this?

You must wrap the $sd with a single quote, and escape the slash in date with a backslash, try this:

sd=$(echo $sd | sed 's/\//\\\//g')
sed -n "$(awk '/'$sd'/ { print NR }' aa.log | head -1),$ p" aa.log

PS: convert month name to number if necessary.

share|improve this answer
when I run it seprately it works ! but when I run it on my script it does not work ! and the error is : sed: -e expression #1, char 1: unknown command: `,' also when i run it with 27/Nov/2002 the out put include non relevant items like 22/Dec/2002 ! :( – matarsak Sep 28 '11 at 8:45
Show me the entire your script. – quanta Sep 28 '11 at 8:48
why when I run it with another date it has error :sed: -e expression #1, char 1: unknown command: `,' sd="27/Dec/2002" sd=$(echo $sd | sed 's/\//\\\//g') sed -n "$(awk '/'$sd'/ { print NR }' serverlog.log | head -1),$ p" serverlog.log – matarsak Sep 28 '11 at 9:01
Actually I found the problem ! the problem is there is no 27/dec/2002 in the log file ! so it should search for the next day ! how should i write this? – matarsak Sep 28 '11 at 9:10
Use grep -c to check the date exist first, then do the next steps. – quanta Sep 28 '11 at 9:15

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.