Skip to content

Lesson 10 of 13 · 20m

Matching Across Lines: Records That Aren't Lines

When records span lines: awk paragraph mode, slurp flags, rg -U, the m-versus-s distinction, and the bounded-lazy idiom for folded text.

grep can't see a stack trace. The exception you need is forty indented lines hanging off one timestamped line, and every line-oriented tool will happily hand you the header and drop the Caused by: that actually names the bug. The fix isn't a cleverer pattern — it's changing what counts as a record.

Paragraph mode: awk's RS=""

Set the record separator to the empty string and blank lines delimit records instead of newlines. Pair it with FS="\n" and each line inside a paragraph becomes a field:

# Print the first line of every paragraph that mentions OOM
awk -v RS="" -F'\n' '/OutOfMemoryError/ { print $1 }' app.log

Java logs, mail headers, and -----BEGIN CERTIFICATE----- blocks all collapse into this shape. It's the cheapest multiline tool because nothing gets slurped — awk still streams.

The inverse exists too: in GNU awk, RS can be a regex, so RS="^2025" treats every line starting with a year as a new record boundary. It's gawk-only and it splits on the separator, not the start of the next record — subtleties like that are why the bounded-lazy idiom below is usually the better tool inside real regex engines.

Slurp the whole file

When records aren't blank-line separated, read everything as one string and let . cross newlines:

perl -0777 -ne 'print "$&\n" while m/BEGIN CERTIFICATE.*?END CERTIFICATE/gs' bundle.pem

-0777 disables the record separator entirely; s (dotall) makes . eat \n; g in while m//g iterates every match. GNU tools have a cousin: grep -z and sed -z use NUL as the record separator, so sed -z 's/foo\nbar/baz/' edits across a line break. GNU-only — BSD sed has no -z.

ripgrep does multiline without you slurping anything:

rg -U 'location ~ \^/api \{\n\s+proxy_pass' nginx.conf        # -U = --multiline
rg -U --multiline-dotall 'BEGIN.*?END' bundle.pem             # dot crosses newlines

m and s solve different problems

  • s changes what . consumes: dotall mode eats newlines.
  • m changes what ^ and $ assert: line edges instead of input edges.
import re
log = "2025-03-14 INFO boot\n    at com.app.Main.run(Main.java:42)\n    at com.app.Main.main(Main.java:10)\n2025-03-14 INFO ready"
stack = re.findall(r"^\s+at .*(?:\n\s+at .*)*", log, re.M)
print(stack)   # ['    at com.app.Main.run(Main.java:42)\n    at com.app.Main.main(Main.java:10)']

m alone doesn't let . span lines; s alone doesn't make ^ mean "start of a line." Multiline work often wants both — for instance re.findall(r"^(?P<ts>\S+ \S+) (?P<rest>.*?)(?=^\S|\Z)", log, re.M | re.S) splits a timestamped log into records by "until the next flush-left line."

The bounded-lazy idiom for folded records

"Until the next line that starts flush-left" is the correct shape for tracebacks and folded headers:

re.findall(r"Traceback.*?(?=\n\S|\Z)", log, re.S)

Lazy .*? bounded by a lookahead — not greedy .*, which eats to the end of the file and hands you one giant match containing everything.

Python's str.splitlines() handles \r\n, \r, \v, \f, and Unicode line boundaries (\u2028, \u2029) — worth knowing before you split on \n by hand. When you need the endings kept, splitlines(keepends=True) preserves them.

Know when to leave lines

CSV quoted fields can contain raw newlines — "notes","line one\nline two". You can't paragraph-mode your way out of that: RFC 4180 says a record ends at a newline outside quotes, which is exactly the state machine a real CSV parser maintains. The when-not-to-regex lesson covers the rest.

Field notes

  • pcre2grep -M does true multiline matching on streams.
  • Slurping a 3 GB log into one string is a choice. awk paragraph mode and rg -U stream; read() + findall does not.
  • PEM blocks, -----BEGIN ...----- sentinels, and YAML folded scalars all match cleanly with a lazy bounded span under s.
  • re.finditer over re.M beats findall when you want to stop at the first good match instead of materializing every one.

Keep reading

Related articles from the SudoSecurity blog.