每隔5分钟使用grep解析日志文件

时间:2018-01-29 06:59:45

标签: java shell grep

我使用trilead ssh2进行ssh连接,并且每5分钟解析一次日志文件。

我正在使用这种语法: -

grep '29/Jan/2018:[0-0][6-6]:[1-2][6-1]' /root/nohup.out>/tmp/nohup.txt

Basicaly我正在构建一个Android应用程序,它将每隔5分钟解析一次日志文件并将其存储到/tmp/nohup.txt中,并将下载并解析它以查找异常并向用户显示这些异常通知等。

String  parsingCommand="grep"+" ' "+day2+"/"+month2+"/"+year2+":"+"["+hour2/10+"-"+hour1/10+"]"+"["+hour2%10+"-"+hour1%10+"]"+":"+"["+minute2/10+"-"+minute1/10+"]"+"["+minute2%10+"-"+minute1%10+"]"+" ' "+"/root/nohup.out"+">"+"/tmp/nohup.txt";

这里,minute1 =从服务器获取当前分钟&分钟2 =分钟减少5分钟

grep '29/Jan/2018:[0-0][6-6]:[1-2][6-1]' /root/nohup.out>/tmp/nohup.txt

在这种情况下,分钟间隔是16-21。

我想我没有使用正确的正则表达式。因为

grep '29/Jan/2018:[0-0][6-6]:[1-2][1-6]' /root/nohup.out>/tmp/nohup.txt

它的工作。

任何帮助将不胜感激。 虽然stackoverflow中已有很多答案: -

grep last 2 minutes of log?

https://superuser.com/questions/439688/how-to-grep-a-log-file-within-a-specific-time-period

2 个答案:

答案 0 :(得分:2)

我会使用非捕获组和"或":

egrep '29/Jan/2018:(?:(?:06:16)|(?:06:17)|(?:06:18)|(?:06:19)|(?:06:20)|(?:06:21))' /root/nohup.out>/tmp/nohup.out

您当前的解决方案也将从06:11获得参赛作品,另一方面从06:20错过参赛作品。

要在组中包含日期甚至会更好。否则你可能会在午夜遇到问题:

egrep '(?:28/Jan/2018:23:59)|(?:29/Jan/2018:00:00)|(?:29/Jan/2018:00:01)|(?:29/Jan/2018:00:02)|(?:29/Jan/2018:00:03)' ...

您可以使用StringBuilder完成此任务:

public String getGrepCommand(final Date start) {
    Calendar cal = Calendar.getInstance();
    StringBuilder bld = new StringBuilder();

    cal.setTime(start);
    for (int i = 0; i < 5; ++i) {
        bld.append("|(?:");
        bld.append(String.format("%1$td/%1$tb/%1%tY:%1$tH:%1$tM", cal.getTime()));
        bld.append(")");
        cal.add(Calendar.MINUTE, 1);
    }

    if (bld.length() > 0) { // should be ;)
        bld.delete(1, 1);
    }

    return bld.toString();

}

答案 1 :(得分:1)

以下输入:

  2018-01-29 08:00:30,393  
  2018-01-29 08:02:00,003   
  2018-01-29 08:03:00,210 
  2018-01-29 08:01:00,401  
  2018-01-29 08:01:00,401  
  2018-01-29 08:05:00,401   
  2018-01-29 08:16:00,002
  2018-01-29 08:17:00,002
  2018-01-29 08:18:00,002
  2018-01-29 08:19:00,002
  2018-01-29 08:20:00,002
  2018-01-29 08:21:00,002

如果您尝试运行此正则表达式:

  2018-01-29 08:(0[0-4]|1[6-9]|2[0-1])

你会看到5分钟的完美比赛。您将不得不使用或运算符进行多模式匹配。重构正则表达式的方式,您将不得不进行大量的计算。为了节省这么多精力,Daniel提供的解决方案根据您的需要是合适的。

相关问题