2017-06-03 123 views
0

我的测试文件看起来像下面awk中匹配的线和打印列多个模式,如果发现其他打印

输入

$ cat file 
date="2017-10-10" ip=192.168.1.1:22 inbound=100 outbound=50 
date="2017-10-10" ip=192.168.1.1:22 inbound=100 
date="2017-10-10" ip=192.168.1.1:22 outbound=60 

我用下面的awk命令来提取值入境=。

$ awk '{found=0; for(i=1;i<=NF;i++) { if ($i ~ /inbound/) { split($i,arr,"="); print arr[2];found=1 } } if (!found) print 0 }' file 
100 
100 
0 

现在我想补充的“IP”,“端口”和“出站”到列表中,这样我的输出看起来像

IP,PORT,INBOUND,OUTBOUND 

192.168.1.1,22,100,50 
192.168.1.1,22,100,0 
192.168.1.1,22,0,60 
+0

收盘为dup,因为我完全告诉你**如何在[我对你最后一个问题的回答]中做到这一点(https://stackoverflow.com/a/44331032/1745001) - 建立数组,然后打印你喜欢的任何值名称。 –

回答

0

什么

awk '{ 
    ip=0; 
    port=0; 
    inbound=0; 
    outbound=0; 
    for(i=1;i<=NF;i++) { 
     if ($i ~ /ip=/) { 
      split($i,arr,"="); 
      split(arr[2],arr2,":"); 
      ip = arr2[1]; 
      port = arr2[2]; 
     } 
     if ($i ~ /inbound/) { 
      split($i,arr,"="); 
      inbound=arr[2]; 
     } 
     if ($i ~ /outbound/) { 
      split($i,arr,"="); 
      outbound=arr[2]; 
     } 
    } 
    print ip "," port "," inbound "," outbound 
}' file