我正在尝试读取 openvpn 状态日志以获取连接的用户。我试过按照答案 here ,但没有运气。
这是我的文件:
OpenVPN CLIENT LIST
Updated,Mon Jul 13 10:53:46 2020
Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since
user123,8.9.10.11:24142,143404433,5616022,Mon Jul 13 10:09:31 2020
ROUTING TABLE
Virtual Address,Common Name,Real Address,Last Ref
192.168.1.2,user123,8.9.10.11:24142,Mon Jul 13 10:53:45 2020
GLOBAL STATS
Max bcast/mcast queue length,1
END
我想要“Common”和“ROUTING”之间的线条,例如:user123,8.9.10.11:24142,143455713,5682214,Mon Jul 13 10:09:31 2020
使用这个:awk '/Common/{flag=1;next}/ROUTING/{flag=0}flag' /pathtomylog/openvpn-status.log
我得到:user123,8.9.10.11:24142,143455713,5682214,Mon Jul 13 10:09:31 2020
192.168.1.2,user123,8.9.10.11:24142,Mon Jul 13 11:00:36 2020
GLOBAL STATS
Max bcast/mcast queue length,1
END
任何帮助表示赞赏。编辑:以下代码完美运行。问题是
Common
的第二个实例.sudo awk '/ROUTING/{flag=""} /^Common/{flag=1;next} flag' Input file
最佳答案
您能否尝试在 GNU awk
中使用所示示例进行以下、编写和测试? .
awk '/ROUTING/{flag=""} /^Common/{flag=1;next} flag' Input_file
为什么 OP 的代码不起作用:第一个标志由 Common
开始的行设置然后再次通过字符串设置 Common
这是在 ROUTING
之后太靠哪个变量 flag
正在重新设置,然后它永远不会取消设置,因为 ROUTING
在第二个之后找不到 Common
因此它从那里打印所有行。所以我改变了正在寻找 /^Common/
的正则表达式这将与 ROUTING
之后的其他行不匹配.说明:为上述添加详细说明。
awk ' ##Starting awk program from here.
/ROUTING/{ ##Checking if a line starts from string ROUTING then do following.
flag="" ##Setting flag value to NULL here. Since we want to STOP printing from here onward.
}
/^Common/{ ##Checking condition if a line starting from Common then do following.
flag=1 ##Setting variable flag to 1 here.
next ##next keyword will skip all further statements from here.
}
flag ##Checking condition if flag is SET then print current line(since no action mentioned so by default printing of current line will happen) here.
' Input_file ##Mentioning Input_file name here.
关于regex - 无法使用 AWK 读取两个模式之间的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62880771/