Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

perl

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

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

Note that because of the s modifier (in m/RE/s), "." is allowed to match newline (along with anything else).

This lets the pattern match the words in the specific order with anything between them (i.e. pattern BEGIN is on one line while pattern END is on a few lines below). If the two patterns are on the same line this works fine, but not when it spans multiple line. What am I missing here?

like image 758
Reza Toghraee Avatar asked Feb 17 '13 20:02

Reza Toghraee


1 Answers

Actually I did figure out the missing part! I needed to use the -0777 option to search through the whole file as on record and print the matched expression using print $& instead:

perl -wln -0777 -e 'm/BEGIN.+END/s and print $&;' < file.txt
like image 69
Reza Toghraee Avatar answered Nov 15 '22 03:11

Reza Toghraee