下面是我试图解析的一个日志文件的示例。
2018-09-09 15:32:28 Alert Server1 Running Check TRIGGERED
+--------------------------------------+---------+
| ID | host | altID | value |
+--------------------------------------+---------+
| 4als4234 | host1.mail.com | isRunning | true |
| 5nsh3463 | host2.mail.com | isRunning | false |
+--------------------------------------+---------+
Instance: server
Alert ID: server_running
我想有一个脚本,运行和格式的日志如下所示:
host: host1.mail.com
altID: isRunning
value: true
Alert ID: server_running
host: host2.mail.com
altID: isRunning
value: false
AlertID: server_running
我对linux有一般的了解,我的bash脚本知识有限。我尝试过使用一些awk命令,但是我似乎不能得到正确的格式。有什么建议吗?
发布于 2018-10-11 20:40:10
检查此Perl解决方案:
$ cat alert.pl
open $INPUT,"<","$ARGV[0]" or die "No such file";
my $alertid ="";
while(my $row = <$INPUT>)
{
if ($row=~m/^[|]\s*\d/m)
{
my @F = split(/\|/, $row);
push @ht,"$F[2]";push @alt,"$F[3]";push @val,"$F[4]";
}
if ($row=~m/^Alert/m)
{
($alertid = $row)=~s/(.*):(.*)/\2/g;
}
}
foreach my $id (0..1)
{
print "host:$ht[$id]\n" ;
print "altID:$alt[$id]\n" ;
print "value:$val[$id]\n" ;
print "AlertID:${alertid}\n" ;
}
$ perl -f alert.pl alert.log // Calling the perl script
host: host1.mail.com
altID: isRunning
value: true
AlertID: server_running
host: host2.mail.com
altID: isRunning
value: false
AlertID: server_running
发布于 2018-10-11 20:55:02
使用GNU awk:
gawk '
/Alert.*TRIGGERED/ {alert_start = NR}
alert_start && NR == alert_start + 4 { # the first data row of the table
while (NF == 9) {
ids[$2]["host"] = $4
ids[$2]["altID"] = $6
ids[$2]["value"] = $8
getline
}
}
alert_start && /^Alert ID/ {
for (id in ids)
printf "host: %s\naltID: %s\nvalue: %s\nAlert ID: %s\n\n",
ids[id]["host"], ids[id]["altID"], ids[id]["value"], $3
delete ids
alert_start = 0
}
' log.file
发布于 2018-10-12 21:21:10
在一条评论中,您说需求Alert-ID 'server1_running" instead of 4als4234
是一个打字错误。
据我所知,在需求中会有一些东西是这样工作的
grep -E "true|false" inputfile |
while read -r _ id _ host _ altID _ value _; do
cat <<@
host: ${host}
altID: ${altID}
value: ${value}
Alert id: ${id}
@
done
这将给出输出
host: host1.mail.com
altID: isRunning
value: true
Alert id: 4als4234
host: host2.mail.com
altID: isRunning
value: false
Alert id: 5nsh3463
https://stackoverflow.com/questions/52767761
复制