As you are using Debian 9 (Stretch), you have the version of pcre2-utils
which includes pcre2grep
10.22. That version doesn't include the -m
or --max-count
option to quit after a certain number of matches. With that being said, what you are trying to do, print up to a string, simply isn't possible with the version that you have.
The version that comes with Debian 11 (Bullseye), 10.34, does have this option. You can use it on the file that you have to achieve the expected output with the following:
pcre2grep -B2 -m1 XXX file
You can also do it with regular grep
as there's no need to use Perl-compatible regular expressions for your case:
grep -B2 -m1 XXX file
The -n
option isn't needed as it just prints the line number which isn't in your expected output and the -M
option conflicts with the -m
option because the former tells it to match multiple lines.
Output of the above commands:
aaa
bbb
XXX
That prints up to the first match of the string XXX
and also the two lines before it; however, I wouldn't recommend this because you'd have to know exactly how many lines appear from the beginning of the line until the string. That might not be an issue for your particular file but would be if the file were to contain thousands or millions of lines.
What you trying to do, in effect, is to print everything from the beginning of the file up to and including a certain string. Neither grep
or any of its derivatives such pcre2grep
are designed to do this and don't have options to get this result in a dependable manner on their own. It is for this reason that it's better to use a tool that is actually designed to achieve this such as sed
or awk
which I've previously mentioned. They are both far more reliable and easier to use to get what you want and don't require any doctoring or having to know exactly how many lines come before where you want the output to stop. You may have gone into this with the intention of using pcre2grep
but it's important to recognize that there are better options and use one of those.
-P
option.pcregrep
andpcre2grep
support multiline matching with-M
,grep
does not.