我已经写了awk来打印来自空格分隔的日志文件的specyfic行。
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编程在我看来并不强烈。我文学上根本不知道如何咬它。
答案 0 :(得分: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"
如果那不是您想要的,那么您需要提供更多信息。