Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grep pattern with Multiple lines with AND operation

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Interface:                      vlan
Status:                         True
Type:                           Master
ID:                             104

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading