How do I grep for multiple patterns? The syntax is: Use single quotes in the pattern: grep 'pattern*' file1 file2. Next use extended regular expressions: egrep 'pattern1|pattern2' *.
Let's break this command down: The -P option enables the PCRE add-on for grep. The -z option treats the matched text as a sequence of lines by adding the NUL character to each line's ending. The -o option enables grep to print only the matched text and ignore trailing spaces.
Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.
Why don't you go for awk:
awk '/Start pattern/,/End pattern/' filename
So I discovered pcregrep which stands for Perl Compatible Regular Expressions GREP.
For example, you need to find files where the '_name' variable is immediatelly followed by the '_description' variable:
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
Here is the example using GNU grep
:
grep -Pzo '_name.*\n.*_description'
-z
/--null-data
Treat input and output data as sequences of lines.
See also here
grep -P
also uses libpcre, but is much more widely installed. To find a complete title
section of an html document, even if it spans multiple lines, you can use this:
grep -P '(?s)<title>.*</title>' example.html
Since the PCRE project implements to the perl standard, use the perl documentation for reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With