在日志文件中使用Bash Grep查找两个日期之间的行

3

我有一个看起来像这样的日志文件:

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.

现在我通过以下方式使用参数调用我的Bash脚本:

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

所以我的问题是:如果我使用时间范围如2015年7月7日11:00至2015年7月8日20:00,我该如何在日志文件中获取两个日期之间的文本?
谢谢。

正如答案中所看到的,grep并不总是工具箱中最合适的工具。awksed也是可用的,而且perl通常已经安装好了。 - Stephen P
3个回答

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

或更一般地说:
sed -n "/$START/,/$END/p"

2
您可以使用 Perl 范围操作符来实现。我假设日志文件已按日期排序。另一个假设是日期格式为 YYYY-MM-DD。
cat logfile | perl -ne 'print if (/2015-07-07 11:00/ .. /2015-07-08 20:00/)'

2

我已经编写了一个测试脚本,对于我来说它是有效的。

#!/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

我可以这样执行它:
./test.sh -t 07.07.2015,12:48:32-07.07.2015,13:01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接