这是我尝试解析的日志文件的示例。
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命令,但似乎无法正确设置格式。有什么建议么?
答案 0 :(得分:0)
检查此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
答案 1 :(得分:0)
使用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
答案 2 :(得分:0)
您在评论中说,要求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