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

●1 ●31 ●95
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 killed the process I started. The port stayed taken.

BashSnippets - Nov 5

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

BashSnippets - Oct 13

The log was deleted. Its 48M was still allocated.

BashSnippets - Oct 28

I deleted 44.6 GB and df moved by 5

BashSnippets - Nov 10
chevron_left
4k Points • 127 Badges
North America • bashsnippets.xyz
77Posts
35Comments
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)

4 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!