regex - 无法使用 AWK 读取两个模式之间的行

标签 regex linux shell awk sed

我正在尝试读取 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/

相关文章:

c++ - 在控制台应用程序中检测按键?

linux - 循环遍历所有具有特定扩展名的文件并对它们执行某些操作

python - 匹配具有相同字符分隔值的日期

java - 搜索和替换定界参数的算法

linux - Linux系统调用层如何跟踪文件的属性变化

c - GTK Linux C 通过按钮小部件从输入框获取输入

linux - 使用 grep、sed 或 awk 解析字符串

mysql - 如何在shell脚本中将MySQL查询输出转换为数组?

Javascript 和 Regex 将时间存储在数组中

PHP 反向 Preg_match