【问题标题】:Can't read lines between two patterns using AWK无法使用 AWK 读取两个模式之间的行
【发布时间】:2020-11-02 22:32:20
【问题描述】:

我正在尝试读取 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 grep:grep -Poz 'Common Name.*\n\K(.|\n)*(?=ROUTING TABLE)' filegrep -Poz '(?<=Connected Since\n)(.|\n)*(?=ROUTING TABLE)' file
  • @Cyrus 感谢这也有效!

标签: regex linux shell awk sed


【解决方案1】:

您能否尝试在 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.

【讨论】:

  • 非常感谢。我什至没有注意到Common 的第二个实例。很好的解释。
  • @NonSequiter,欢迎您,很高兴我能帮助您。继续学习并继续在这个伟大的论坛上分享欢呼:)
猜你喜欢
  • 2019-09-28
  • 2023-01-13
  • 2013-08-21
  • 1970-01-01
  • 2020-03-02
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多