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

●1 ●19 ●78
calendar_today • 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.

2 Comments

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

More Posts

My 30-day log cleanup kept a file that was 30 and a half days old

BashSnippets - Oct 8

I escaped the dot correctly and sed still rewrote a file marked DO NOT CHANGE

BashSnippets - Oct 13

bash ran a path that no longer existed, and exited 127

BashSnippets - Oct 21

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
chevron_left
3.8k Points • 98 Badges
North America • bashsnippets.xyz
68Posts
31Comments
10Connections
Linux user who got tired of Googling the same bash commands every time I sat down at a terminal. Sta... Show more

Related Jobs

Commenters (This Week)

1 comment
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!