Plainnotes

sed -i differs between macOS and Linux

2025-10-15 · 2 min readTools

A script works on Linux and fails on macOS with sed: 1: "file": invalid command code f.

BSD sed requires a backup suffix with -i: sed -i '' 's/a/b/' file, where the empty string means no backup. GNU sed takes the expression directly and -i.bak keeps a backup.

Either detect the platform:

if sed --version >/dev/null 2>&1; then
  sed -i 's/a/b/' file
else
  sed -i '' 's/a/b/' file
fi

or use perl -pi -e 's/a/b/' file, which behaves the same on both.

In general, copy the file before -i, especially with greedy patterns — there is no undo.