macのsedで"extra characters after \ at the end of a command"やら"command i expects \ followed by text"で出る時の対応
結論
- MacのsedはBSD版で、LinuxのGNU版sedと仕様が違う
- brew install gnu-sedでGNU版のsedを入れる
- PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"でPATHを通すと、sedコマンドを置換できる
内容
シェルスクリプトで先頭の行に文字列の挿入をしたかったが、下記のエラーが出てしまう。
$ sed -i '' '1i\\\encoding UTF-8' sample.sql sed: 1: "1i\\\encoding UTF-8": extra characters after \ at the end of i command
調べていくとMacのsedコマンドはBSD版で、GNU版と仕様が異なる部分がいくつかあるという話らしい。
対処法
$ 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`).
まとめ
仕様違いとは知らず、時間を無駄に...
先人に感謝。