macOS sed refuses a newline inside s///; do multi-line edits with python
PitfallVerified 29 Sep 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.
Symptom#
A scripted multi-line replacement such as sed -i '' '0,/^#include <x>/s//line1\nline2/' file fails on macOS with sed: 1: "...": unescaped newline inside substitute pattern, and no file is changed.
Cause#
BSD sed cannot take a literal newline inside a substitute command's pattern or replacement. GNU sed on Linux is more permissive, so the same one-liner works there.
Fix#
For any edit whose search or replacement text contains a newline, use a small python script (read, str.replace or re, write) instead of sed.
Evidence#
dftracer-utils session, 2026-09-29: a sed loop that inserted an #include line before the first existing include failed on 4 files with the error above. The same edit done with a python read-and-insert loop worked, and the following build was clean.
Also found by searching
- sed -i '' 's/foo/line1\nline2/' file -> sed: 1: "...": unescaped newline inside substitute pattern
- sed one-liner inserting two lines works on Linux but fails on my Mac and changes nothing
- how do I do a multi-line search and replace in a file on macOS without BSD sed errors
- BSD sed vs GNU sed newline in replacement string, gsed not installed, alternative for scripted edit
- sed: 1: "...": unescaped newline inside substitute pattern
- sed -i '' with \n in the replacement fails on my Mac but works on Linux
- how do I insert multiple lines with sed on macOS bsd sed in a script
- gnu sed vs bsd sed newline in s command, need a portable multiline replace for many files