Using perl as the best grep to match multiple lines using m / RE / s single line mode

I am trying to grep for text between expressions (say BEGIN and END ) that may not be on the same line:

 perl -wln -e 'm/BEGIN.+END/s and print;' < file.txt 

Please note that due to the s modifier (in m/RE/s ) "." allowed to match a new line (along with anything else).

This allows the template to combine words in a specific order with something in between (i.e., the BEGIN template is on the same line, and the END template is on the few lines below). If two patterns are on the same line, this works fine, but not when it spans multiple lines. What am I missing here?

+4
source share
1 answer

In fact, I found out the missing part! I needed to use the -0777 to search the entire file, as well as write, and print the matching expression with print $& instead:

 perl -wln -0777 -e 'm/BEGIN.+END/s and print $&;' < file.txt 
+6
source

All Articles