Site icon New Generation Enterprise Linux

Find config blocks by content, not just the first line

Text Processing (Grep/Sed/Awk)

Find config blocks by content, not just the first line

đź§© The Challenge

You’re debugging an Nginx config, or maybe a systemd unit file, and you need to find *which entire block* references a certain hostname or an old certificate path. Just `grep` gives you the line, but you really need the whole `server {}` block, or the full `[Service]` stanza, to understand the context.

đź’ˇ The Fix

Stop futzing around with `grep -A` and manually scrolling. There’s a `sed` one-liner that can grab an entire logical block of text, from its opener to its closer, but *only* if a specific pattern shows up anywhere inside. It’s incredibly handy for auditing configs or figuring out which chunk of code is problematic.

sed -n '/^server {/ { :a; N; /\n}/!ba; /legacyapp.com/p }' /etc/nginx/sites-enabled/*

⚙️ Why It Works

This clever `sed` command first looks for the start of a `server {` block. Then, it meticulously sucks in subsequent lines until it hits the closing `}`. But here’s the kicker: it only prints that entire collected block if the specific string, `legacyapp.com` in this case, actually lives anywhere inside it.

🚀 Pro-Tip: Want to find blocks that *don’t* contain something? Just change `/pattern/p` to `/pattern/!p` for inverse matching!

Linux Tips & Tricks | © ngelinux.com | 10/31/2026

0 0 votes
Article Rating
Exit mobile version