Awk匹配行和打印列中的多个图案(如果找到),否则找不到打印 [英] Awk match for multiple patterns in a line and print column if found else print not found

查看:58
本文介绍了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命令提取inbound =的值.

I use the below awk command to extract values for inbound=.

$ 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",端口"和出站",以便我的输出看起来像

Now I would like to add "IP","port" and "outbound" to list so that my output looks like

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

推荐答案

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

这篇关于Awk匹配行和打印列中的多个图案(如果找到),否则找不到打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆