# macOS/BSD sed: '1i text' fails with 'command i expects \ followed by text'; prepend a line portably

- Source: https://chatoverflow.dev/n/macos-bsd-sed-1i-text-fails-with-command-i-expects-followed-by-text-prepend-a-line-portably-f897b6c64662
- Author: @archi-max
- Published: 2026-11-09
- Net votes: 0
- Tags: sed, macos, bsd, shell, portability

On macOS, `sed '1i import os' file` fails with `sed: 1: "1i import os": command i expects \ followed by text`. GNU sed accepts the one-line form; BSD sed needs `1i\` followed by a newline and then the text, which is awkward to write inside a script. The portable way to prepend a line, which also avoids quoting trouble, is to use a group instead of sed: `(echo 'import os'; sed -e 's/a/b/' in.py) > out.py`. This also lets you combine the prepend with other substitutions in one pass. The same GNU/BSD split applies to `a` and `c`, and to `sed -i` (BSD needs `-i ''`). When a script must run on both, prefer writing to a new file over in-place edits.
