【发布时间】:2017-06-14 11:57:31
【问题描述】:
我是awk 和perl 的新手,所以请多多包涵。
我有以下awk 脚本:
awk '/regex1/{p = 0;} /regex2/{p = 1;} p'
这基本上是打印从与 regex2 匹配的行开始的所有行,直到找到与 regex1 匹配的行。
例子:
regex1
regex2
line 1
line 2
regex1
regex2
regex1
输出:
regex2
line 1
line 2
regex2
是否可以使用perl 单线来模拟这种情况?我知道我可以使用保存在文件中的脚本来做到这一点。
编辑:
一个实际的例子:
2017 年 5 月 24 日 17:00:06,827 [INFO] 123456 (Blah : Blah1) Service-name:: 单行内容
2017 年 5 月 24 日 17:00:06,828 [INFO] 567890 (Blah : Blah1) 服务名称:: 内容(可能跨越多行)
2017 年 5 月 24 日 17:00:06,829 [INFO] 123456 (Blah : Blah2) 服务名称:多行内容。打印对象[ ID1=fac-adasd ID2=123231
ID3=123108 状态=未知
代码=530007 目的地=CA
]2017 年 5 月 24 日 17:00:06,830 [INFO] 123456 (Blah : Blah1) Service-name:: 单行内容
2017 年 5 月 24 日 17:00:06,831 [INFO] 567890 (Blah : Blah2) 服务名称:: 内容(可能跨越多行)
给定搜索键 123456 我想提取以下内容:
2017 年 5 月 24 日 17:00:06,827 [INFO] 123456 (Blah : Blah1) Service-name:: 单行内容
2017 年 5 月 24 日 17:00:06,829 [INFO] 123456 (Blah : Blah2) 服务名称:多行内容。打印对象[ ID1=fac-adasd ID2=123231
ID3=123108 状态=未知
代码=530007 目的地=CA
]2017 年 5 月 24 日 17:00:06,830 [INFO] 123456 (Blah : Blah1) Service-name:: 单行内容
以下 awk 脚本可以完成这项工作:awk '/[0-9]{2}\s\w+\s[0-9]{4}/{n = 0} /123456/ {n =1}n' file
【问题讨论】:
-
你知道有一个可以尝试的程序 awk2perl 吗?
-
对于 awk,请参阅 stackoverflow.com/a/38972737/4082052 以获得更好的方法...如果您知道如何编写 perl 脚本,请参阅 stackoverflow.com/documentation/perl/3696/… 和 perldoc.perl.org/perlrun.html#Command-Switches .. 你会想要使用 perldoc.perl.org/perlop.html#Range-Operators