I want to match a multiline regex and print only the lines that match:
$ cat test.txt
line1
line2
line3
$ perl -ne 'print if /line2.line3/s' test.txt
$
This regex actually matches line2\nline3
but it is not printed. regex101 verifies that it is matched.
Using command switch 0777
prints the lines that match but then it prints non-matched lines too:
$ perl -0777 -ne 'print if /line2.line3/s' test.txt
line1
line2
line3
Using 0777
in a substitution regex works as expected:
$ perl -0777 -pe 's/line2.line3/replaced/s' test.txt
line1
replaced
I would like to learn if it is possible to print only lines that match a multiline regex?
print
without an argument prints $_
. If you use -0777
, the whole file is read into $_
, so if there is a match, you print the whole file. If you only want to show the matching parts, you can use
perl -0777 -ne 'print "$1\n" while /(line2.line3)/sg' test.txt