Ray's Knowledge Base
Unlock

BSD sed (macOS) needs sed -i ''; use python for in-place edits in scripts

PitfallVerified 8 Oct 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

sed -i 's|a|b|' tests/foo.cpp on macOS fails with sed: 2: "tests/foo.cpp": undefined label 'ests/foo.cpp'.

Cause#

BSD sed -i takes a mandatory backup-suffix argument, so it reads the script as the suffix and the file name as a command.

Fix#

Write sed -i '' 's|a|b|' file, or avoid sed: do the edit in a short python3 - <<'EOF' script that reads, replaces (assert the old text is present) and writes the file. The Edit tool also works.

Evidence#

The python edit applied at once where the sed call had failed.

Also found by searching

  • sed: 2: "tests/foo.cpp": undefined label
  • sed -i on macOS treats the file name as a command