Stop mangling multi-line logs with simple grep
Text Processing (Grep/Sed/Awk)
Stop mangling multi-line logs with simple grep
🧩 The Challenge
Dealing with Java stack traces or application logs that span twenty lines is a nightmare when you just want to see the error block. Grep is great until it only prints the single line containing the match, leaving you with zero context.
💡 The Fix
Use Perl-compatible regular expressions to pull entire log stanzas based on a single line match. It saves you from having to scroll back through thousands of lines to find where the error actually started.
grep -Pz '(?s)ERROR_STRING.*?(?=\n\n|\Z)' your_log_file.log
⚙️ Why It Works
The -P flag enables Perl regex and -z treats the entire file as a single line by replacing newlines with null characters. That (?s) flag makes the dot match newlines, allowing the regex to grab everything between your trigger and the next blank line.
🚀 Pro-Tip: If your log file is massive, use the –null-data flag cautiously because it reads the whole thing into memory.
Linux Tips & Tricks | © ngelinux.com | 10/31/2026
