Grep 获取数字范围

Grep 获取数字范围

您将如何在日志文件中搜索日期范围?

日志文件如下所示:

01/14 00:00:01  INFO:     received connect request from 10.10.10.10 

我需要将日志压缩为 10 分钟,从 8:25 开始一直持续到 8:35

当我使用以下egrep时,我发现太多结果,例如00:08:25 01:08:25......08:25:00

我怎样才能08:25:00通过08:35:59

我尝试过的

cat foo | egrep "08:2[5-9]|08:3[0-5]"
cat foo | egrep "08:2[5-9]:??|08:3[0-5]:??"
cat foo | egrep "08:2[5-9]:[0-9][0-9]|08:3[0-5]:[0-9][0-9]"

答案1

这应该会产生期望的结果。

egrep "08:[2][5-9]:[0-5][0-9]|08:[3][0-5]:[0-5][0-9]" foo

cat在这种情况下不需要使用。

答案2

通过这些输入:

01/15 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 08:25:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 08:35:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10

您可以使用以下命令打印两个图案之间的所有行awk

awk -v date='01/14' '$1!=date{next};/08:25/,/08:35/' logfile

01/14 08:25:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 00:00:01  INFO:     received connect request from 10.10.10.10
01/14 08:35:01  INFO:     received connect request from 10.10.10.10

答案3

如果您愿意使用sed,您可以:

sed -n '/^01\/14 08:00/,/^01\/14 08:10/p' foo

一般来说,你可以使用bash变量替换上面命令中的具体时间。例如:

st="01\/14 08:00"
en="01\/14 08:25"
sed -n "/^$st/,/^$en/p" foo #note the double quotes

您需要使用 if 用作分隔/符来转义字符,如上面的命令所示。\/

答案4

你可以使用perl。下面对时间字段执行词法比较,这意味着即使您没有包含开始或结束时间的行,它也可以工作。

 yourprogram | perl -lane 'print if $F[1] ge "08:25:00" and $F[1] lt "08:36:00"'

这假设时间是输入中的第二个字段,并且格式为hh:mm:ss

您还可以通过添加另一个条件来指定日期:

 yourprogram | perl -lane 'print if $F[1] ge "08:25:00" and $F[1] lt "08:36:00" and $F[0] eq "01/14"'

输入是使用以下脚本生成的:

for ((h=8;h<9;h++)); do
  for ((m=20;m<40;m=m+2)); do
    for ((s=0;s<60;s=s+10)); do
      printf "01/14 %02d:%02d:%02d line %d\n" $h $m $s $((++l))
    done
  done
done

执行中

bash script | perl -lane 'print if $F[1] ge "08:25:00" and $F[1] lt "08:36:00"'

产生:

01/14 08:26:00 line 19
01/14 08:26:10 line 20
01/14 08:26:20 line 21
01/14 08:26:30 line 22
01/14 08:26:40 line 23
01/14 08:26:50 line 24
01/14 08:28:00 line 25
01/14 08:28:10 line 26
01/14 08:28:20 line 27
01/14 08:28:30 line 28
01/14 08:28:40 line 29
01/14 08:28:50 line 30
01/14 08:30:00 line 31
01/14 08:30:10 line 32
01/14 08:30:20 line 33
01/14 08:30:30 line 34
01/14 08:30:40 line 35
01/14 08:30:50 line 36
01/14 08:32:00 line 37
01/14 08:32:10 line 38
01/14 08:32:20 line 39
01/14 08:32:30 line 40
01/14 08:32:40 line 41
01/14 08:32:50 line 42
01/14 08:34:00 line 43
01/14 08:34:10 line 44
01/14 08:34:20 line 45
01/14 08:34:30 line 46
01/14 08:34:40 line 47
01/14 08:34:50 line 48

相关内容