LoginSignup
8
7

More than 5 years have passed since last update.

sed で上書き保存する場合の注意

Last updated at Posted at 2015-02-08

sed で拡張正規表現 (Extended regular expressions) を使った際にハマったのでメモ。

結論

GNU sed (4.2.2) で -r または -E オプション(拡張性表現)と -i オプション(上書き保存)を同時に使う場合、 -ire-iE のようにまとめて指定してはいけない。
-i -re-i -E と別々に指定しなければならない。

2015/02/08 追記
-i に続く文字はバックアップファイルのサフィックスとして認識されてしまうため、拡張正規表現を使う場合以外でも 常に別々に指定しなければならなかった (詳細はコメント欄を参照)。

確認

GNU sed のバージョンは次の通り。

$ sed --version
sed (GNU sed) 4.2.2
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Jay Fenlason, Tom Lord, Ken Pizzini,
and Paolo Bonzini.
GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <bug-sed@gnu.org>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

以下のようなファイルを生成して、拡張正規表現の有無で動作の違いを確認する。

$ echo "hogehoge" > sample.txt
$ cat sample.txt
hogehoge

拡張正規表現なしの場合

拡張正規表現を使用しない場合、 -ie のようにまとめて指定しても問題ない。

$ sed -ie 's/^\(hoge\)/\1fuga/g' sample.txt
$ cat sample.txt
hogefugahoge

拡張性表現ありの場合

拡張正規表現を使用する場合、 -ire-iE のようにまとめて指定するとうまくいかない。

$ sed -ire 's/^(hoge)/\1fuga/g' sample.txt
sed: -e expression #1, char 18: invalid reference \1 on `s' command's RHS
$ cat sample.txt
hogehoge

一方、 -i -re-i -E のようにオプションを別々に指定するとうまく動く。

$ sed -i -re 's/^(hoge)/\1fuga/g' sample.txt
$ cat sample.txt
hogefugahoge
8
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7