Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

Why does `sed -i` behave differently on macOS and Linux?

IntermediateConceptText processing: grep, sed, awk, cut, sort, uniq
Answer

GNU sed's -i takes an optional, attached suffix (-i or -i.bak). BSD/macOS sed requires a suffix argument, so sed -i 's/a/b/' f treats the expression as the suffix and the filename as the script: sed: 1: "f": invalid command code f.

sed -i.bak 's/a/b/' f && rm f.bak   # works on both
sed -i '' 's/a/b/' f                # macOS only

In CI and containers we are on GNU sed; on laptops, install gnu-sed (gsed) or use the portable form.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq