LoginSignup
12
12

More than 5 years have passed since last update.

macでテキスト置換をsedで行う

Posted at

sedのテキスト置換後のファイルの上書きではまった箇所があるのでメモ。

sedでテキスト置換する時は-iオプションでこんな感じで書く
bash
sed -i -e "s/置換したい文字列/置換後の文字列/g" [置換するファイル]

ただ、上記のコマンドを使ってmacのターミナルで置換すると痛い目を見る。

macの場合

$ echo hoge > hoge.txt; sed -i -e "s/hoge/fuga/g" hoge.txt; cat hoge.txt; ls -l | grep hoge
fuga
-rw-r--r-- 1 louis Users 5 Dec 5 19:30 hoge.txt
-rw-r--r-- 1 louis Users 5 Dec 5 19:30 hoge.txt-e
$ cat hoge.txt-e
hoge

-eを語尾につけたファイルをバックアップとして作成してくれている。

sed -iのオプションとして''空文字を指定してやると回避出来る

echo hoge > hoge.txt; sed -i '' -e "s/hoge/fuga/g" hoge.txt; cat hoge.txt; ls -l | grep hoge
fuga
-rw-r--r-- 1 louis Users 5 Dec 5 19:39 hoge.txt

ただ、-iのオプションとして渡す時に半角スペースを入れないとご丁寧に-eを語尾につけたファイルをバックアップとして作成してくれる。

linuxのsedの場合は-iの後に''を指定する必要は無いけど、もしつけた場合は-iとオプションの間に半角スペースを入れては行けない。

12
12
1

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
12
12