goldenmean
goldenmean

Reputation: 19026

Regex to search a multi-line field in a text file

I have a text file of logs. In it I am interested in searching a field using some regular expression (I use notepad++ on Win, but even use vim on Ubuntu to parse/read this log text file so either one is ok)

The text file has entries as below.

src.type= DEVICE_1     <-- there is a space and then a newline char after the last letter which is 1
dst.type= ZONE_1
someparam1

src.type= DEVICE_1 
dst.type= ZONE_2
someparam2

Such entries keep repeating in the log text file.

I am interested in finding those lines which have DEVICE_1 in it but only for those occurrences which have a dst.type= ZONE_2 after it i.e.

I intend to find

src.type= DEVICE_1 
dst.type= ZONE_2

but not

src.type= DEVICE_1
dst.type= ZONE_1

Notepad++ allows searching using keywords as regexes. I could get a working regex or any other way (not necessarily involving regexes) to find such occurrences I am looking for in the text file.

I tried below in notepad++ search using regex without success:

src.type= DEVICE_1 \ndst.type= ZONE_2

Also tried [ ] character class.

How can I search for what I am looking to find?

Upvotes: 1

Views: 246

Answers (3)

romainl
romainl

Reputation: 196876

In Vim, the following pattern seems to match what you want:

DEVICE_1\s*\n.*ZONE_2

Use /DEVICE_1\s*\n.*ZONE_2 to jump to the next match.

Use :g/DEVICE_1\s*\n.*ZONE_2/command to execute command on each match.

Use :vim DEVICE_1\s*\n.*ZONE_2 % | cw to list all the matches in the quicfix window.

Note that you can easily reuse the latest search pattern with //. It is a common strategy to work on your search pattern with /foo and, once you are satisfied, perform a substitution like this:

:%s//bar

Upvotes: 2

Alexander Shukaev
Alexander Shukaev

Reputation: 17019

There you go for Vim:

/^\zssrc.type= DEVICE_1\ze\_.\{2,2}\_^dst.type= ZONE_2$/

Breakdown of important expressions:

  1. \zs - Start match here (will be highlighted from here);
  2. \ze - End match here (will be highlighted to here);
  3. \_. - same as ., but new line is also included;
  4. \_^ - like ^, but \_ is required because we are in the middle of regular expression.

For others, I'd refer you to Vim's documentation.

Upvotes: 0

m4573r
m4573r

Reputation: 990

In Notepad++, use the following regex, with the ". matches newlines" checkbox enabled:

src.type= DEVICE_1\s+dst.type= ZONE_2

enter image description here

Upvotes: 1

Related Questions