grep string并查找日志文件中没有任何更改,写入CSV文件

时间:2017-11-29 19:29:42

标签: shell awk split match

我有一个输入文件(generator_file.log):

[+++]          Added names:          [+++]
     -> Add- response.names (3):
     -> Add- chat.names (2):
     -> Add- events.names (2):
[///]     Modified active rules:     [///]
     -> Mod- events.names (2):
     -> Mod- mal.names (1):
[---]         Removed names:         [---]
     -> Del- chat.names (2):
     -> Del- events.names (8):
     -> Del- jan.names (4):

,预期输出应如下所示:

Add,response,3
Add,chat,2
Add,events,2
Del,chat,2
Del,events,8
Del,jan,4
Total no of Added Names: 7
Total no of Deleted Names: 14

以下是我试过的shell脚本但没有获得所需的输出:

egrep "Del-|Add-" generator_file.log |awk '
BEGIN{Addname=0; Delname=0;}
{
      if(match($0,"Add-")>0)
       {
         split($0,addcountb,"(");
         split(addcountb[2], addcount, ")");
         Addname+=addcount[1] ;
       }
     if(match($0,"Del-")>0)
      {
         split($0,delcountb,"(");
         split(delcountb[2], delcount, ")");
         Delname+=delcount[1] ;
      }
}
END {print "Number of names Added: "Addname; print "Number of names Deleted: "Delnames;}'

1 个答案:

答案 0 :(得分:0)

awk救援!

$ awk -F' +|[-.()]' -v OFS=, '{c=$(NF-1)} 
                       /Del-/ {del+=c; f=1} 
                       /Add-/ {add+=c; f=1} 
                       f      {print $4,$6,c; f=0} 
                       END    {print "Added: " add; 
                               print "Deleted: " del}' file

Add,response,3
Add,chat,2
Add,events,2
Del,chat,2
Del,events,8
Del,jan,4
Added: 7
Deleted: 14

或可能是

$ awk -F' +|[-.()]' -v OFS=, '/(Del|Add)-/{c=$(NF-1); cs[$4]+=c;
                                           print $4,$6,c}
                              END         {print "Added: "   cs["Add"];
                                           print "Deleted: " cs["Del"]}' file