带有多行和操作的GREP模式
我该如何确定与GREP在多条线上存在的模式?以下是我需要检查的多行模式
状态:正确 类型:主
我尝试了以下命令,但它检查了一行上的多个字符串,但是在多行文件上,字符串模式匹配失败
if cat file.txt | grep -P '^(?=.*Status:.*True)(?=.*Type:.*Master)'; then echo "Present"; else echo "NOT FOUND"; fi
.txt
接口:VLAN 状态:正确 类型:主 ID:104
How can I determine a pattern exists over multiple lines with grep? below is a multiline pattern I need to check is present in the file
Status: True Type: Master
I tried the below command but it checks multiple strings on a single line but fails for strings pattern match on multiple lines
if cat file.txt | grep -P '^(?=.*Status:.*True)(?=.*Type:.*Master)'; then echo "Present"; else echo "NOT FOUND"; fi
file.txt
Interface: vlan Status: True Type: Master ID: 104
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
gnu-grep
您可以执行此操作:说明:
p
:启用PCRE REGEX模式-Z
:读取Multiline输入-o
:仅打印匹配的数据(?m)
启用多行模式,以便我们可以在每行^
之前使用Using
gnu-grep
you can do this:Explanation:
P
: Enabled PCRE regex mode-z
: Reads multiline input-o
: Prints only matched data(?m)
Enables MULTILINE mode so that we can use^
before each line^
: Start a line使用您显示的样本,请尝试以下内容
AWK
程序。在gnuawk
中编写和测试。说明: 简单的说明将设置
rs
(记录awk
)为Regex(^|) \ n)状态:[[:space:]]+true \ ntype:[:space:]]+Master
(下面说明),在主程序中检查rt
是否不是然后用rt
中删除新线(启动一个),并使用rt
的null和打印值,以获取OP显示的预期输出。With your shown samples, please try following
awk
program. Written and tested in GNUawk
.Explanation: Simple explanation would be setting
RS
(Record separator ofawk
) as regex(^|\n)Status:[[:space:]]+True\nType:[[:space:]]+Master
(explained below) and in main program checking ifRT
is NOT NULL then remove new line(starting one) inRT
with NULL and print value ofRT
to get expected output shown by OP.我做的如下:
-a x
表示“还显示x
lines a a 找到一个。-b y
的意思是“还显示y
lines b 在找到一个。一个(“类型”一个),然后与上一个(“状态”)一起显示“类型”行。
I did it as follows:
The
-A x
means "also show thex
lines After the found one.The
-B y
means "also show they
lines Before the found one.So: show the "Status" line together with the next one (the "Type" one), and then show the "Type" line together with the previous one (the "Status" one).
您还可以在End
Prev = $ 0
的每条线路中跟踪上一行的设置,并使用模式匹配上一行和当前行。输出
You could also keep track of the previous line setting in every line at the end
prev = $0
and use a pattern to match the previous and the current line.Output