简体   繁体   中英

Perl does not match multiple lines

I want to match:

Start Here Some example
text covering a few
lines. End Here

So I do

$ perl -nle 'print $1 if /(Start Here.*?)End Here/s'

then paste the text above and ctr-D . It wont match from cmd - but it does in file script. Why?

Change input record separator ( $/ ) to null using -0 command line switch.

perl -0777nle 'print $1 if /(Start Here.*?)End Here/s' <<END
Start Here Some example
text covering a few
lines. End Here
THE_END

man perlrun

-0[octal/hexadecimal]
specifies the input record separator ($/) as an octal or hexadecimal number. […] Any value 0400 or above will cause Perl to slurp files whole, but by convention the value 0777 is the one normally used for this purpose.

man perlvar

IO::Handle->input_record_separator( EXPR )
$INPUT_RECORD_SEPARATOR
$RS
$/
The input record separator, newline by default. This influences Perl's idea of what a "line" is. […] You may set it to […] "undef" to read through the end of file.

As others have explained, you're reading your file a line at a time, so matches over multiple lines are never going to work.

Reading files a line at a time is often the best approach. So we can use the "flip-flip" operator to do this:

 $ perl -nle 'print if /Start Here/ .. /End Here/' your_file_here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM