
[ad_1]
grep
is a command line text searching utility capable of finding patterns and strings in files and other types of input. Most matches will only match on a single line, but it’s often useful to match across multiple newlines.
Grep. match in multiple new lines with
handling multi-line matches is something grep
struggles with. There is a better tool for the job awk
either sed
, both of which naturally handle multi-line input. Using two expressions with a comma between them will match everything between those two patterns.
awk '/from/,/to/' file sed -n '/from/,/to/p' file
it’s still possible to handle grep
However, the order is very clumsy.
grep -Pz '(?s)from.*n.*to' test
It does a few things:
-P
turns on Perl Compatible Regex,-z
Feeds the entire file as a single line with “zero bytes” instead of a newline. This allows grep to process the whole thing as a single line.(?s)
turns on PCRE_DOTALL, which creates.
character matches any character, including newlines.from
It’s the opening match..*n.*
as long as everything matchesto
Which is the end of the match.
Overall, this will accomplish this for scripting purposes, but it’s enough to remember if you’re typing it yourself. In addition, using -o
The flag to print only the match will also print a trailing zero byte character, which can cause additional problems.
Using pcre2grep instead (perl-compatible grep)
Regular grep
is not the best tool for the job, and there is an alternative called pcre2grep
It has support for Perl Compatible Regular Expressions out of the box, and is able to match multiline regexes very easily.
It’s probably installed on your system, but if it isn’t, you can get it from your package manager:
sudo apt install pcre2-utils
Then, you just need to run -M
parameter.
pcre2grep -M 'from(n|.)*to' file
Note that this still requires you to manually match “newlines or any characters” (n|.)*
, Alternatively, you can use (?s)
The trick is to turn on PCRE_DOTALL and also match the dot character to newlines.
pcre2grep -M '(?s)from.*to' file
[ad_2]
Source link
[ad_2]
#find #pattern #matches #multiple #lines #grep
Most Reliable Software Company in Kolkata , West Bengal , India
#itservicesinkolkata #bestsoftwarecompanyinkolkata