【问题标题】:search pattern in file and print following lines containing other pattern在文件中搜索模式并打印以下包含其他模式的行
【发布时间】:2015-03-04 23:50:03
【问题描述】:

我已经编写了 awk 来打印以空格分隔的日志文件中的特定行。

if [ ! -f $userlog ]
then
awk -F' ' '$7$8 == "Loginitialized" {print $2" "$3" "$4" "$5" process start"}''$7$8$9 == "Applictionsuccessfullyended" {print $2" "$3" "$4" "$5" process end"}' $preplog > $userlog
fi

输出样本(用户日志)

2015-03-02 13:14:25 (PID 19594) process start
2015-03-02 22:42:29 (PID 30473) process start
2015-03-02 22:53:20 (PID 30473) process end
2015-03-03 07:16:55 (PID 31078) process start
2015-03-03 14:53:15 (PID 16591) process start
2015-03-03 14:54:10 (PID 18292) process start

我需要在 $preplog 上使用相同的 awk,但从最后一行开始,我已经用它打印了。 我正在尝试,但我失败了:

if [ -f $userlog ]
then
lastpid=`awk -F' ' 'END{print $4}' $userlog`        #pid ostatniego procesu
cat $preplog | awk 'BEGIN{ found=0} /PID /$lastpid/ Log initialized/{found=1}  {if (found) {awk -F" " "$7$8 == "Loginitialized" {print $2" "$3" "$4" "$5" process start"}''$7$8$9 == "Applictionsuccessfullyended" {print $2" "$3" "$4" "$5" process end"}"} ;}' >> $userlog
fi

但我的 awk 编程能力并不强。我真的不知道如何咬它。

【问题讨论】:

  • 不是很清楚你想要什么,你能根据你之前的样本添加预期的输出吗?
  • 通常的解决方法是使用日志轮换,并在轮换时分析旧的日志文件。

标签: bash awk sed


【解决方案1】:

让我们从清理你当前的脚本开始:

awk -F' ' '$7$8 == "Loginitialized" {print $2" "$3" "$4" "$5" process start"}''$7$8$9 == "Applictionsuccessfullyended" {print $2" "$3" "$4" "$5" process end"}' $preplog > $userlog

将其更改为:

awk '
   $7$8 == "Loginitialized" { state="start" }
   $7$8$9 == "Applictionsuccessfullyended" { state="end" }
   state { print $2, $3, $4, $5, "process", state; state="" }
' "$preplog" > "$userlog"

为了提高稳健性和清晰度,并删除不必要的结构和冗余。

对于您接下来想要做什么 - 看看阅读 https://stackoverflow.com/a/18409469/1745001 是否有帮助,如果没有帮助,请编辑您的问题以显示示例输入和预期输出以及更清晰、更详细的说明您正在尝试做什么。

等一下,我想我在重新阅读您尝试的代码段后得到了一个启示 - 也许您想要的只是分析和操作输入文件的最后一行,而不是它的每一行。如果是这样,那就是:

awk '
   { var1=$7$8; var2=$7$8$9 }
   END {
       if (var1 == "Loginitialized") { state="start" }
       if (var2 == "Applictionsuccessfullyended") { state="end" }
       if (state) { print $2, $3, $4, $5, "process", state; state="" }
   }
' "$preplog" > "$userlog"

如果这不是您想要的,您需要提供更多信息。

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 2012-09-25
    • 2016-07-13
    • 2015-02-16
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多