日志文件中两个日期之间的 Bash Grep 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31470843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:21:01  来源:igfitidea点击:

Bash Grep lines between 2 dates in log file

linuxbashshell

提问by ramana_k

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:

现在我用这样的参数调用我的 bash 脚本:

./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?

所以我的问题是:如果我使用像 2015-07-07 11:00 到 2015-07-08 20:00 这样的时间范围,我如何获得日志文件中两个日期之间的文本?

Thanks

谢谢

采纳答案by ramana_k

I have written a test script, that works for me

我写了一个测试脚本,这对我有用

#!/bin/bash

startDate=$(echo  | cut -d "-" -f 1 | cut -d "," -f 1)
endDate=$(echo  | cut -d "-" -f 2 | cut -d "," -f 1)
startTime=$(echo  | cut -d "-" -f 1 | cut -d "," -f 2)
endTime=$(echo  | 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

回答by Fiximan

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

or more general:

或更一般的:

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

回答by ramana_k

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.

您可以为此使用 Perl 范围运算符。我假设日志文件按日期排序。另一个假设是日期的格式为 YYYY-MM-DD。

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