Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to grep multiline search patterns in Linux?
In Linux, searching for multiline patterns requires special techniques beyond the basic grep command. While grep is designed primarily for single-line pattern matching, we can use various approaches and tools to search across multiple lines effectively.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It displays lines that contain the pattern we are trying to search, where the pattern is referred to as a regular expression.
Basic Grep Syntax
grep [options] pattern [files]
Common options include −
-c : Count of lines that match the pattern -h : Display matched lines only -i : Ignore case for matching -l : Print filenames only -n : Display matched lines with line numbers -v : Print lines that do not match the pattern -r : Recursively search subdirectories
Single Directory Search
To find a pattern in all files within a directory −
grep -rni "func main()" *
This command searches for "func main()" in all files recursively, ignoring case and showing line numbers.
main.go:120:func main() {}
To search only in the current directory (not subdirectories) −
grep -s "func main()" *
Multiline Pattern Search Methods
Consider this sample file sample.txt −
$ cat sample.txt blabla blabla foofoo here is the text2strike Just a pattern bar blabla blabla
Method 1: Using grep with Perl Regex (-P)
grep -Pzo "foofoo[\s\S]*?bar" sample.txt
Method 2: Using pcregrep for Multiline
pcregrep -M "foofoo.*?\nbar" sample.txt
Method 3: Using sed for Range Matching
sed -n '/foofoo/,/bar/p' sample.txt
foofoo here is the text2strike Just a pattern bar
Method 4: Using awk for Complex Patterns
awk '/foofoo/,/bar/' sample.txt
Advanced Techniques
| Tool | Best For | Syntax Example |
|---|---|---|
| grep -Pzo | Simple multiline with null separation | grep -Pzo "pattern1.*pattern2" |
| pcregrep -M | Complex multiline regex | pcregrep -M "pattern1.*\npattern2" |
| sed -n | Range-based matching | sed -n '/start/,/end/p' |
| awk | Pattern ranges and logic | awk '/start/,/end/' |
Key Points
Standard grep works line-by-line; use
-Pflag for multiline with Perl regexThe
-zoption treats input as null-separated records instead of newline-separatedpcregrepprovides more advanced multiline capabilities than standard grepsedandawkare excellent alternatives for range-based multiline searches
Conclusion
Multiline pattern searching in Linux requires tools beyond basic grep, such as grep with Perl regex, pcregrep, sed, or awk. Each method has its strengths − choose based on pattern complexity and performance requirements. The sed range method is often the most readable for simple start-to-end pattern matching.
