awk多线问题

时间:2011-08-01 00:27:08

标签: bash awk

一直在尝试编写一个处理日志文件的awk脚本,但我正在苦苦挣扎。

我有一个文件,其行如下所示:

[2011-07-29 04:44:37.100 INFO] AU/SUB1/Server:WebHits : Hits[ABC]=0; Hits[DEF]=876; Hits[THY]=0; Hits[SG]=891; Hits[XFRR]=1386
[2011-07-29 04:44:37.599 INFO] AU/SUB2/Server:WebHits : Hits[XARR]=0; Hits[XXX]=0; Hits[ABS]=0; Hits[SM]=0
[2011-07-29 04:44:37.699 INFO] AU/MAIN/Server:Main : Hits=254
[2011-07-29 04:44:38.100 INFO] AU/SUB1/Server:WebHits : Hits[ABC]=0; Hits[DEF]=1134; Hits[THY]=0; Hits[SG]=1153; Hits[XFRR]=426
[2011-07-29 04:44:38.599 INFO] AU/SUB2/Server:WebHits : Hits[XARR]=0; Hits[XXX]=0; Hits[ABS]=0; Hits[SM]=22
[2011-07-29 04:44:38.699 INFO] AU/MAIN/Server:Main : Hits=436

正如您所看到的,每秒有三行(每秒总有三行)。我想组合这些行(每秒一行),以便摘要看起来像这样,因此输入日志文件中有三行摘要相关器:

[2011-07-29 04:44:37 INFO] MainHits=254,ABC=0,DEF=876,THY=0,SG=891,XFRR=1386,XARR=0,XXX=0,ABS=0,SM=0
[2011-07-29 04:44:38 INFO] MainHits=436,ABC=0,DEF=1134,THY=0,SG=1153,XFRR=426,XARR=0,XXX=0,ABS=0,SM=22

请注意场地名称,例如: “ABC,DEF,THY,SG等”可以动态变化。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

解决方案在很大程度上依赖于您发布的输入格式:

awk '/Main :/ {
  sub(/\.[0-9]*/, x, $2)
  print $1, $2, $3, "Main" $NF, r
  r = x; next
  }
{
  gsub(/Hits\[/, x)
  gsub(/[];]/, x)
  for (i = 5; ++i <= NF;)
    r = r ? r "," $i : $i
  }' infile 

答案 1 :(得分:2)

使用sed的隐秘解决方案:

sed -e 'N;N;s/\n\[.\{28\}\]/;/g;s/\.... INFO/ INFO/;s!AU/SUB1/Server:WebHits : !!;s!AU/SUB2/Server:WebHits : !!;s!AU/MAIN/Server:Main : !!;s/ INFO\] \(.*\) Hits=\(.*\)/ INFO\] MainHits=\2 \1/;s/ Hits\[\([^]]*\)\]=\([^;]*\);/,\1=\2/g' infile

这值得一些解释,因此下面是注释的脚本文件版本。必须使用'sed -f script infile'

运行
# Read 2 more lines, so we will have 3 lines are in the pattern space.
N
N
# Change the timestamps of the 2 extra lines by a ;.
s/\n\[.\{28\}\]/;/g
# Remove the milliseconds of the remaining timestamp, and the extra data of each line.
s/\.... INFO/ INFO/
s!AU/SUB1/Server:WebHits : !!
s!AU/SUB2/Server:WebHits : !!
s!AU/MAIN/Server:Main : !!
# Generate the MainHits data.
s/ INFO\] \(.*\) Hits=\(.*\)/ INFO\] MainHits=\2 \1/
# Format the Hits data.
s/ Hits\[\([^]]*\)\]=\([^;]*\);/,\1=\2/g
相关问题