sed 's/port/listen_port/g' rewrote four lines of a four-line config

●1 ●9 ●62
calendar_today ago • schedule1 min read

A four-line YAML file (port: 8080, support_email, transport: tcp, report_dir: /var/reports) and the rename most people type first: sed -i 's/port/listen_port/g' app.yml. GNU sed 4.9 exited 0 and printed nothing, because -i never does. Afterwards the file held suplisten_port_email, translisten_port and /var/relisten_ports. One line was meant to change. All four did.

sed matches characters, not words. The letters p-o-r-t sit inside support, transport and report, and g replaced every occurrence. GNU sed's \b word boundary fixes the match, and one pipe shows the damage before anything is written:

sed 's/\bport\b/listen_port/g' app.yml | diff app.yml -

Without -i the file on disk stays intact, and diff prints the lines that would change. It exits 1 when it finds differences, so the same check works inside a script. Only after the diff reads right does -i go back on.

Two caveats before trusting \b. Underscore counts as a word character, so db_port stays untouched. And \b is a GNU extension: BSD sed on macOS spells word boundaries [[:<:]] and [[:>:]], and its -i requires a suffix argument (sed -i '') where GNU's is optional.

The replacement side bites too. An unescaped & means the whole match, so s/CEO/Smith & Sons/ produces Smith CEO Sons.

The bulk-replace script, with a grep -rl file list, per-file diff and an --apply gate that fails toward reading, is on the sed find-and-replace snippet page.

🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

ShellCheck rates SC2086 as info. It let rm delete two files I never named.

BashSnippets - Sep 29

My Nginx Died at 2 AM and Nobody Noticed for 6 Hours. Now I Have a Watchdog Script

BashSnippets - May 21

Who owns that port? One ss flag answers it without sudo

BashSnippets - Sep 16

I sent my report script SIGTERM mid-write. Yesterday's output survived intact.

BashSnippets - Sep 24

Three Lines of Bash Stand Between Your Cron Job and a Silent Outage

BashSnippets - Jul 5
chevron_left
3.5k Points • 72 Badges
North America • bashsnippets.xyz
62Posts
26Comments
7Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

View all jobs →

Commenters (This Week)

8 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!