とりあえずコード書けよ

技術的なことの備忘録。

macのsedで"extra characters after \ at the end of a command"やら"command i expects \ followed by text"で出る時の対応

結論
内容

シェルスクリプトで先頭の行に文字列の挿入をしたかったが、下記のエラーが出てしまう。

$ sed -i '' '1i\\\encoding UTF-8' sample.sql
sed: 1: "1i\\\encoding UTF-8": extra characters after \ at the end of i command

調べていくとMacsedコマンドはBSD版で、GNU版と仕様が異なる部分がいくつかあるという話らしい。

it-ojisan.tokyo

対処法

GNUsedをhomebrewでインストールする

$ brew install gnu-sed

特に何もしなければgnu-sedを使うコマンドはgsedとなるが、使い勝手がイマイチ。
homebrewでのインストール完了後にも表記が出るが、下記のPATHを通すとsedコマンドを置換できる。

GNU "sed" has been installed as "gsed".
If you need to use it as "sed", you can add a "gnubin" directory
to your PATH from your bashrc like:

    PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"
==> Summary
🍺  /usr/local/Cellar/gnu-sed/4.9: 12 files, 628.6KB
==> Running `brew cleanup gnu-sed`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
まとめ

仕様違いとは知らず、時間を無駄に...
先人に感謝。