【问题标题】:Reading contents of log file and calculating in shell scripting读取日志文件的内容并在 shell 脚本中计算
【发布时间】:2017-11-11 07:53:10
【问题描述】:

我想实现一个提供以下功能的 shell 脚本程序:

  • 它需要一个日志文件作为输入。日志文件包含带有消息标记的日志语句,如下所示。
  • 该实用程序列出所有花费超过指定时间的操作。时间从命令行以秒为单位指定。

输入:

#<process id> <date time> <log level> <file name> <line number> <actual message>

1098 2007-02-28 15:23:09 WARN db_util.c 5928 Config file not found, using default values
1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:17 INFO db_util.c 5908 Connected to database
1098 2007-02-28 15:23:17 ERROR log_test.c 198 Unable to setup our satellite launch system
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite
1098 2007-02-28 15:23:21 INFO log_test.c 198 Reconnected. Initialize to launch the satellite.

E. G。如果通过将输入文件作为输入和 2 秒的性能阈值时间来执行实用程序,它应该产生以下输出:

1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite

【问题讨论】:

  • 只是为了澄清起见,当下一行出现超过 2 秒时,您正在寻找要打印的行(在此示例中,尽管秒数取决于用户输入)?
  • 是的。没错。

标签: bash shell


【解决方案1】:

在 bash 脚本中使用 awk:

#!/bin/bash
awk -v threshold=$1 '{texttime=mktime(gensub(/-|:/," ", "g", $2" "$3))} NR>1 && texttime-prevtexttime>threshold{print prevrecord} {prevtexttime=texttime; prevrecord=$0}' $2

$1 是您的阈值时间(以秒为单位),$2 是您的日志文件

这个 awk 脚本是:

  1. 将变量 threshold 设置为 $1 (-v threshold=$1) 中的任何内容
  2. 将当前记录的日期和时间转换为 unix 时间戳 (mktime(gensub(/-|:/," ", "g", $2" "$3))) 并将其存储在 awk 变量 texttime (texttime=) 中。可能有一种更优雅的方式来做这件事,我之前没有在awk 中处理过日期和时间。如果这是丑陋的做法,我敢肯定@edmorton 会让我直截了当。
  3. 如果我们不处理第一条记录 (NR&gt;1) 并且 texttime 变量中的值减去 prevtexttime 变量中的值大于我们的 threshold 变量中的值 (texttime-prevtexttime&gt;threshold ) 然后打印变量 prevrecord (print prevrecord) 中的值。
  4. 处理完记录后,将变量prevtexttime 设置为texttime 中的值,并将变量prevrecord 设置为此记录的内容$0 (prevtexttime=texttime; prevrecord=$0)
  5. 对于$2 中指定的任何文件

【讨论】:

  • 非常感谢内维尔。惊人的解释,非常清楚每个命令和术语的用法。代码按预期工作。
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2021-08-31
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多