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
CodePudding user response:
Using gnu-grep
you can do this:
grep -zoP '(?m)^\s*Status:\s True\s Type:\s Master\s*' file
Status: True
Type: Master
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
CodePudding user response:
With your shown samples, please try following awk
program. Written and tested in GNU awk
.
awk -v RS='(^|\n)Status:[[:space:]] True\nType:[[:space:]] Master' '
RT{
sub(/^\n/,"",RT)
print RT
}
' Input_file
Explanation: Simple explanation would be setting RS
(Record separator of awk
) as regex (^|\n)Status:[[:space:]] True\nType:[[:space:]] Master
(explained below) and in main program checking if RT
is NOT NULL then remove new line(starting one) in RT
with NULL and print value of RT
to get expected output shown by OP.
CodePudding user response:
I did it as follows:
grep -A 1 "^.*Status:.*True" test.txt | grep -B 1 "^Type:.*Master"
The -A x
means "also show the x
lines After the found one.
The -B y
means "also show the y
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).