macOS High Sierraでsedで上書き更新しようとして-iオプションを付けて実行したらsed: 1: "ファイルパス": invalid command code mとなったときの対応方法


上書き更新するときは「''」を引数に入れる
$ sed -i '' 's/hoge/fuga/g' {ファイルパス}
  • 環境
    • OS:macOS High Sierra バージョン10.13.6
    • sed:BSDのsed

事象:sedに-iオプションを付けて実行したらsed: 1: "ファイルパス": invalid command code mとなった

$ sed -i 's/シェル/shell/g' ~/Desktop/shell_kind.sh 
sed: 1: "/Users/mana/Desktop/she ...": invalid command code m

理由:BSDのsedはバックアップ用の拡張子を指定しなければならないから

GNUのsedはなくていいけどBSDのsedは必要。

$ man sed
<省略>
     -i extension
             Edit files in-place, saving backups with the specified extension.  If a zero-length extension is given,
             no backup will be saved.  It is not recommended to give a zero-length extension when in-place editing
             files, as you risk corruption or partial content in situations where disk space is exhausted, etc.
<省略>

$ ls -l ~/Desktop/
total 8
-rw-r--r--@ 1 mana  staff  199  9 17 16:13 shell_kind.sh # <<< 変更前の内容のファイル
# こんな感じに使う
$ sed -i '.bak' 's/*/-/g' ~/Desktop/shell_kind.sh 
$ ls -l ~/Desktop/
total 16
-rw-r--r--  1 mana  staff  199  9 18 20:45 shell_kind.sh # <<< 変更された内容のファイル
-rw-r--r--@ 1 mana  staff  199  9 17 16:13 shell_kind.sh.bak # <<< 変更前の内容がバックアップとしてできる

対応方法:「''」を引数に追加する。

$ sed -i '' 's/シェル/shell/g' ~/Desktop/shell_kind.sh