user4066693
user4066693

Reputation:

Bash Grep lines between 2 dates in log file

I have a log file that looks like this:

2015-07-07 11:23:33,006 DEBUG : Invoking handleMessage on interceptor org.apache.cxf.interceptor.LoggingInInterceptor@2798240a

name="New Test User"
domicile="A Place"
name="Test User"

2015-07-07 15:00:33,008 DEBUG : Invoking handleMessage on interceptor org.apache.cxf.interceptor.

Now i call my bash script with a paramter like this:

./test.sh -t 2015-07-07,11:00-2015-07-08,20:00.

So my question is: How can i get the text between the two dates in the log file if i use my time range like 2015-07-07 11:00 until 2015-07-08 20:00?

Thanks

Upvotes: 3

Views: 11326

Answers (3)

user4066693
user4066693

Reputation:

I have written a test script, that works for me

#!/bin/bash

startDate=$(echo $2 | cut -d "-" -f 1 | cut -d "," -f 1)
endDate=$(echo $2 | cut -d "-" -f 2 | cut -d "," -f 1)
startTime=$(echo $2 | cut -d "-" -f 1 | cut -d "," -f 2)
endTime=$(echo $2 | cut -d "-" -f 2 | cut -d "," -f 2)

#Script Parameter Format to search in Log Files: DD.MM.YYYY,hh:mm-DD.MM.YYYY,hh:mm
timestampStart=$(echo $startDate | cut -d "." -f 3)-$(echo $startDate | cut -d "." -f 2)-$(echo $startDate | cut -d "." -f 1)" "$startTime
timestampEnd=$(echo $endDate | cut -d "." -f 3)-$(echo $endDate | cut -d "." -f 2)-$(echo $endDate | cut -d "." -f 1)" "$endTime

tStart=`date --date="$timestampStart" +%s`
tEnd=`date --date="$timestampEnd" +%s`

while read line; do
  re="[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}"
  if [[ $line =~ $re ]]; then
    searchDate=$(echo $line | cut -d "," -f 1)
    tSearch=`date --date="$searchDate" +%s`
  fi

  if [ $tSearch -ge $tStart ] && [ $tSearch -lt $tEnd ];then
    echo $line
  fi
done < logs/backup/log/my_test.log

and i can execute it like this:

./test.sh -t 07.07.2015,12:48:32-07.07.2015,13:01

Upvotes: 2

ramana_k
ramana_k

Reputation: 1933

You can use Perl range operator for this. I am assuming that the log file is sorted by date. Another assumption is that dates are in the format YYYY-MM-DD.

cat logfile | perl -ne 'print if (/2015-07-07 11:00/ .. /2015-07-08 20:00/)'

Upvotes: 2

FelixJN
FelixJN

Reputation: 570

sed -n "/2015-07-07 11:23:33/,/2015-07-07 15:00:33/p"

or more general:

sed -n "/$START/,/$END/p"

Upvotes: 6

Related Questions