sedでcommand i expects \ followed by textが出た

環境

$sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.6
BuildVersion:   18G95

概要

sedを実行したら下記エラーが出た

$cat test.txt
1
2
3
#2行目にhogeを挿入
$cat test.txt | sed -e 2ihoge
command i expects \ followed by text

原因

Mac(BSD)とLinux(GNU)のsedの振る舞いが異なるため。
macos linux sedなどで調べると出てくる。

対応

gnu-sedを使う(BSD用の書き方もあるがLinux環境を考慮した。)

$brew install gnu-sed
$echo "alias sed='gsed'" >> .bashrc
$ source ~/.bashrc